Python爬蟲連載13-BeatuifulSoup四大對象、遍歷文檔對象、CSS選擇器

1、BeautifulSoup四大對象node

1.Taggit

(1)對應的就是Html中的標籤;github

(2)能夠經過soup,tag_name正則表達式

(3)tag裏面有兩種重要的屬性微信

name:用於打印標籤的名字學習

attrs:用於打印屬性(返回一個字典)大數據

contents:打印內容(返回一個列表)ui

 

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.NavigableStringurl

對應內容值spa

3.BeautileSoup

(1)表示的是一個文檔的內容,大部分能夠把它看成是tag對象

(2)通常能夠使用soup來表示

4.Comment

(1)特殊類型的NavagableString對象

(2)對其輸出,則內容不包括註釋符號

2、遍歷文檔對象

1.contents:tag的子節點以列表的方式給出

2.children:子節點以迭代器的方式返回

3.decendants:全部的孫子節點

4.string

3、搜索文檔對象

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)

4、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)

5、源碼

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.歡迎關注微信公衆號:傅里葉變換,我的公衆號,僅用於學習交流,後臺回覆」禮包「,獲取大數據學習資料

 

相關文章
相關標籤/搜索