一、BeautifulSoup四大對象 1.Tag (1)對應的就是Html中的標簽; (2)可以通過soup,tag_name (3)tag裡面有兩種重要的屬性 name:用於列印標簽的名字 attrs:用於列印屬性(返回一個字典) contents:列印內容(返回一個列表) from bs4 i ...
一、BeautifulSoup四大對象
1.Tag
(1)對應的就是Html中的標簽;
(2)可以通過soup,tag_name
(3)tag裡面有兩種重要的屬性
name:用於列印標簽的名字
attrs:用於列印屬性(返回一個字典)
contents:列印內容(返回一個列表)
from bs4 import BeautifulSoup from urllib import request url = "http://www.baidu.com" rsp = request.urlopen(url) content = rsp.read() soup = BeautifulSoup(content) #bs自動轉碼 content = soup.prettify() print(content) print("==" *12) print(soup.head) print("=="*12) print(soup.link.name) print("=="*12) print(soup.link.attrs) print(soup.link.attrs["type"]) print("=="*12) print(soup.title) print(soup.title.name)#列印標簽 print(soup.title.attrs) print(soup.title.contents)#列印內容,返回一個列表
2.NavigableString
對應內容值
3.BeautileSoup
(1)表示的是一個文檔的內容,大部分可以把它當作是tag對象
(2)一般可以使用soup來表示
4.Comment
(1)特殊類型的NavagableString對象
(2)對其輸出,則內容不包括註釋符號
二、遍歷文檔對象
1.contents:tag的子節點以列表的方式給出
2.children:子節點以迭代器的方式返回
3.decendants:所有的孫子節點
4.string
三、搜索文檔對象
find_all(name,attrs,recursive,text,**kwargs)
name:按照哪個字元串搜索,可以傳入的內容:
(1)字元串;(2)正則表達式;(3)列表
kewwortd參數,可以用來表示屬性
text:對應tag的文本值
from bs4 import BeautifulSoup from urllib import request import re url = "http://www.baidu.com" rsp = request.urlopen(url) content = rsp.read() soup = BeautifulSoup(content) #bs自動轉碼 content = soup.prettify() for node in soup.head.contents: if node.name == "meta": print(node) print("=="*12) tags = soup.find_all(name=re.compile("meta"))#可以使用正則,返回了一個列表,找的是含有meta屬性的所有標簽 print(tags) print("=="*12)
四、CSS選擇器
1.使用soup.select,返回一個列表
2.通過標簽名稱:soup.select("title")
3.通過類名:soup.select(".content")
4.通過id名:soup.select("#name_id")
5.組合查找:soup.select("div #input_content")
6.屬性查找:soup.select("img[class="photo"])
7.獲取tag內容:tag.get_text
from bs4 import BeautifulSoup from urllib import request import re url = "http://www.baidu.com" rsp = request.urlopen(url) content = rsp.read() soup = BeautifulSoup(content) print(soup.prettify()) print("=="*12) titles = soup.select("title") print(titles[0]) print("=="*12) metas = soup.select("meta[content='always']") print(metas)
五、源碼
Reptile13_1_BeautifulSoupFourComponent.py
Reptile13_2_TraverseFileObject.py
Reptile13_3_CSSSelector.py
https://github.com/ruigege66/PythonReptile/blob/master/Reptile13_1_BeautifulSoupFourComponent.py
https://github.com/ruigege66/PythonReptile/blob/master/Reptile13_2_TraverseFileObject.py
https://github.com/ruigege66/PythonReptile/blob/master/Reptile13_3_CSSSelector.py
2.CSDN:https://blog.csdn.net/weixin_44630050
3.博客園:https://www.cnblogs.com/ruigege0000/
4.歡迎關註微信公眾號:傅里葉變換,個人公眾號,僅用於學習交流,後臺回覆”禮包“,獲取大數據學習資料