一、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[])
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.歡迎關注微信公眾號:傅里葉變換,個人公眾號,僅用于學習交流,后臺回復”禮包“,獲取大資料學習資料
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/179643.html
標籤:Python
