python網絡爬蟲(5)BeautifulSoup的使用示范

創建并顯示原始內容

其中的lxml第三方解釋器加快解析速度

import bs4
from bs4 import BeautifulSoup
html_str = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title"><b>The Dormouse's story</b></p>
<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1"><!-- Elsie --></a>,
<a href="http://example.com/lacie" class="sister" id="link2"><!-- Lacie --></a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>
<p class="story">...</p>
"""
soup = BeautifulSoup(html_str,'lxml')
print(soup.prettify())

控制臺顯示出soup需要處理的內容:

?

提取對象內容和屬性

搜索包括了所有的標簽。默認提取第一個符合條件的標簽。

提取Tag對象

其中,name用于顯示標簽名,去掉name則內容直接顯示。

print(soup.name)
print(soup.title.name)
print(soup.title)
print(soup.a)

控制臺輸出效果如下:

顯示屬性

attrs用于顯示屬性。class用于顯示選中的標簽Tag中的類名。

print(soup.p['class'])
print(soup.p.attrs)

輸出結果:

內容文字

顯示標記中的文字,NavigableString類型

print(soup.p.string)
print(type(soup.p.string))

效果:

顯示注釋

顯示注釋內容,注意與普通string的區別在于最后的類,用于數據分類

print(soup.a.string)
print(type(soup.a.string))

?

文檔相關結點

直接子節點數組

結點中的contents輸出直接子節點數組,可以通過for逐個輸出,通過string屬性直接輸出內容

print(soup.body.contents)

輸出body標簽下的直接子節點:

結點children輸出直接子節點,和contents類似。不一樣的是返回了生成器,一點參考:https://www.cnblogs.com/wj-1314/p/8490822.html

for i in soup.body.children:print(i,end='')

添加了end=''用于去掉print的自動換行

子、孫節點

結點descendants可以輸出子節點和孫節點

for i in soup.body.descendants:print(i)

效果:

節點strings輸出全部子節點內容值

print(soup.strings)
print('------------------------') for text in soup.strings:print(text,end='')

效果:

節點stripped_strings輸出全部內容并去掉回車和空格

for text in soup.stripped_strings:print(text)

print每次輸出加上換行后,效果:

父節點相關

父節點parent

print(soup.title)
print(soup.title.parent)

效果:

父輩節點parents,這里只輸出名字就好了,否則內容過多

for i in soup.a.parents:print(i.name)

效果:

兄弟節點等

兄弟節點next_sibling,previous_sibling,另有 :next_siblings,previous_siblings

print(soup.p.next_sibling.next_sibling)
print(soup.p.previous_sibling)

效果:

前后節點:next_element,next_elements等......

?

BeautifulSoup的搜索方法

包括了find_all,find,find_parents等等,這里只舉例find_all。

find_all中參數name查找名稱標記

查找所有b標簽

print(soup.find_all('b'))

輸出:

查找所有b開頭的標簽

配合正則表達式使用

import re
for tag in soup.find_all(re.compile("^b")):print(tag.name)

輸出:

查找a開頭和b開頭的標簽

print(soup.find_all(["a", "b"]))

輸出:(一個數組,過長)

查找所有標簽,True可以匹配任何值

for tag in soup.find_all(True):print(tag.name)

輸出:

自定義過濾

查找含有class和id屬性的Tag標簽

def hasClass_Id(tag):return tag.has_attr('class') and tag.has_attr('id')
print(soup.find_all(hasClass_Id))

效果:

查找關鍵詞參數kwargs并輸出

查找id參數為link2的標簽

print(soup.find_all(id='link2'))

輸出:

查找鏈接中含有elsie的標簽

配合正則表達式

print(soup.find_all(href=re.compile("elsie")))

輸出:

查找所有有id屬性的標簽

print(soup.find_all(id=True))

輸出:

查找所有a標簽且class內容為sister

print(soup.find_all("a", class_="sister"))

輸出:

查找所有鏈接含有elsie的標簽,id為link1

print(soup.find_all(href=re.compile("elsie"), id='link1'))

輸出:

不能表達的屬性的解決方案

在html5中有些屬性不被支持,查找時,通過定義字典實現輸出

data_soup = BeautifulSoup('<div data-foo="value">foo!</div>','lxml')
print(data_soup.find_all(attrs={"data-foo": "value"}))

輸出:

通過text參數查找文本內容并過濾

?輸入:

print(soup.find_all(text=["Tillie", "Elsie", "Lacie"]))
print(soup.find_all(text=re.compile("Dormouse")))

輸出:

通過limit參數限制查找數量

輸入:

print(soup.find_all("a", limit=2))

輸出只有兩個:

通過recursive參數只查找直接子節點

soup位于根處

print(soup.find_all("title"))
print(soup.find_all("title", recursive=False))

輸出:

使用CSS選擇器查找

#直接查找title標簽
print soup.select("title")
#逐層查找title標簽
print soup.select("html head title")
#查找直接子節點
#查找head下的title標簽
print soup.select("head > title")
#查找p下的id="link1"的標簽
print soup.select("p > #link1")
#查找兄弟節點
#查找id="link1"之后class=sisiter的所有兄弟標簽
print soup.select("#link1 ~ .sister")
#查找緊跟著id="link1"之后class=sisiter的子標簽
print soup.select("#link1 + .sister")print soup.select(".sister")
print soup.select("[class~=sister]")print soup.select("#link1")
print soup.select("a#link2")print soup.select('a[href]')print soup.select('a[href="http://example.com/elsie"]')
print soup.select('a[href^="http://example.com/"]')
print soup.select('a[href$="tillie"]')
print soup.select('a[href*=".com/el"]')

?輸出:

?

轉載于:https://www.cnblogs.com/bai2018/p/10964702.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/393430.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/393430.shtml
英文地址,請注明出處:http://en.pswp.cn/news/393430.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

Mingw編譯DLib

Mingw編譯DLib 因為機器上安裝了qt-opensource-windows-x86-mingw530-5.8.0&#xff0c;所以準備使用其自帶的mingw530來編譯DLib使用。 因為DLib使用CMake的構建腳本&#xff0c;所以還請先安裝好CMake。 cmake的下載地址如下https://cmake.org/files/v3.7/cmake-3.7.2-win64-…

探索JavaScript的關閉功能

Discover Functional JavaScript was named one of the best new Functional Programming books by BookAuthority!“發現功能JavaScript”被BookAuthority評為最佳新功能編程書籍之一 &#xff01; A closure is an inner function that has access to the outer scope, even…

QueryList 配置curl參數 的文檔位置 QueryList抓取https 終于找到了

需要設置ssl證書&#xff0c;或者不驗證證書&#xff0c;例&#xff1a;$ql QueryList::get(https://...,[],[verify > false]);設置這個 verify > false , 所以curl的其他參數就在這里配置即可 文檔在 https://guzzle-cn.readthedocs.io/zh_CN/latest/request-optio…

leetcode981. 基于時間的鍵值存儲(treemap)

創建一個基于時間的鍵值存儲類 TimeMap&#xff0c;它支持下面兩個操作&#xff1a; set(string key, string value, int timestamp) 存儲鍵 key、值 value&#xff0c;以及給定的時間戳 timestamp。 2. get(string key, int timestamp) 返回先前調用 set(key, value, times…

物聯網筆記

轉載于:https://www.cnblogs.com/16-C-kai/p/6596682.html

關于大學生玩網絡游戲的調查問卷

1.創建問卷&#xff0c;輸入調查名稱 2編輯問卷 3檢查問卷&#xff0c;是否有誤 4.提交并發布問卷 5分享問卷 6.問卷分析 轉載于:https://www.cnblogs.com/dzw1996/p/7786754.html

java自動排序_java ArrayList自動排序算法的實現

前幾天寫的那個是錯誤的&#xff0c;在這里將正確的更新。。。通過實現ComParator接口&#xff0c;并且對Compare函數進行重寫&#xff0c;自定義排序規則實現對ArrayList中對象的排序。。Student類定義&#xff1a;通過右鍵-》source-》自動生成Set和get方法package first;imp…

1到100的二進制編碼_每天經過100天的編碼后,我學到了什么

1到100的二進制編碼Eleftheria Batsou is a web developer from Thessaloniki, Greece. She gave a talk at the Codegarden conference about her experience doing a solid 100 days of coding every day as part of the #100DaysOfCode Challenge.Eleftheria Batsou是來自希…

第六次 實驗

轉載于:https://www.cnblogs.com/P201821440005/p/10967987.html

leetcode658. 找到 K 個最接近的元素(二分法)

給定一個排序好的數組&#xff0c;兩個整數 k 和 x&#xff0c;從數組中找到最靠近 x&#xff08;兩數之差最小&#xff09;的 k 個數。返回的結果必須要是按升序排好的。如果有兩個數與 x 的差值一樣&#xff0c;優先選擇數值較小的那個數。 示例 1: 輸入: [1,2,3,4,5], k4,…

du命令、df命令用法

一、du命令 [plain] view plaincopy print?[rootwc1 mysql]# du --help Usage: du [OPTION]... [FILE]... or: du [OPTION]... --files0-fromF Summarize disk usage of each FILE, recursively for directories. Mandatory arguments to long options are mandatory…

mysql 循環創建列_mysql – 查詢列中的循環值

我需要創建一個查詢,一次只將一列的值移動一行↑&#xff1a;----------------------------| anotherCOL | values_to_loop |----------------------------| 1 | 1 || 2 | 2 || 3 | 3 || 4 | 4 || 5 | 5 || 6 | 6 || 7 | 7 || 8 | 8 || 9 | 9 || 10 | 10 |--------------------…

因子個數與因子和

題目&#xff1a;LightOJ:1341 - Aladdin and the Flying Carpet(因子個數&#xff09; Its said that Aladdin had to solve seven mysteries before getting the Magical Lamp which summons a powerful Genie. Here we are concerned about the first mystery. Aladdin was …

如何在JavaScript中直觀地設計狀態

by Shawn McKay肖恩麥凱(Shawn McKay) 如何在JavaScript中直觀地設計狀態 (How to visually design state in JavaScript) 使用狀態機和狀態圖開發應用程序的路線圖 (A roadmap for developing applications with state machines & statecharts) Why does state managemen…

SQL Server 2008 - Cannot set a credential for principal 'sa'.

很久沒有用到SQL Server了&#xff0c;今天有幸在幫同事解決一個SQL Server數據連接的問題時突然發現我無法修改我的sa用戶的密碼了。過程是這樣的&#xff1a;一開始我本地的數據庫實例是Windows認證方式&#xff0c;我想將它改成Windows和數據庫混合認證方式后用sa賬戶登錄&a…

leetcode50. Pow(x, n)(快速冪)

實現 pow(x, n) &#xff0c;即計算 x 的 n 次冪函數。 示例 1: 輸入: 2.00000, 10 輸出: 1024.00000 代碼 class Solution {public double myPow(double x, int n) {long tn;return t>0?Pow(x,t):1/Pow(x,-t);//判斷冪指數}public double Pow(double x, long n) {if(n…

Java DES 加解密(DES/CBC/PKCS5Padding)

/*** DES加密** param data 加密數據* param key 密鑰* return 返回加密后的數據*/public static byte[] desEncrypt(byte[] data, String key, String charset) {try {Cipher cipher Cipher.getInstance("DES/CBC/PKCS5Padding");byte[] k charset null || char…

mysql 連接池 100_mysql的最大連接數默認是100_MySQL

mysql的最大連接數默認是100, 這個數值對于并發連接很多的數據庫應用是遠遠不夠的&#xff0c;可以把它適當調大&#xff0c;mysql的最大連接數默認是100, 這個數值對于并發連接很多的數據庫應用是遠遠不夠的&#xff0c;可以把它適當調大&#xff0c;whereis safe_mysqld找到s…

angular上傳圖片_如何使用Angular輕松上傳圖片

angular上傳圖片by Filip Jerga由Filip Jerga 如何使用Angular輕松上傳圖片 (How to make image upload easy with Angular) This is the second part of the tutorial on how to upload an image to Amazon S3. You can find the first part here. In this article, we will …

Java小知識-----Map 按Key排序和按Value排序

Map排序的方式有很多種&#xff0c;這里記錄下自己總結的兩種比較常用的方式&#xff1a;按鍵排序(sort by key)&#xff0c; 按值排序(sort by value)。 1、按鍵排序 jdk內置的java.util包下的TreeMap<K,V>既可滿足此類需求&#xff0c;向其構造方法 TreeMap(Comparator…