爬蟲基礎(四)Beautiful Soup

2021-10-02 15:02:51 字數 2937 閱讀 1323

beautiful soup

# 選擇方法

1、find # 單選

2、find_all # 多項選擇 返回列表

-def

find_all

(self,name =

none

,attrs=

,recursive =

true

,text =

none,limint =

none

,**kwargs)

# css常用選擇器

soup = beautifulsoup(html_doc,

'lxml'

)# 1、通過標籤名查詢

print

(soup.select(

'a')

)# 2、通過類名查詢

print

(soup.select(

'.sister'))

# 3、通過id查詢

print

(soup.select(

'#link1'))

# 4、組合查詢(p標籤中,id 等於link1的內容,二者需要用空格分開)

print

(soup.select(

'p #link1'))

# 5、直接子標籤查詢,使用 > 分隔

print

(soup.select(

'head > title'))

# 6、通過屬性查詢

print

(soup.select(

'a[href = ""]'))

soup = beautifulsoup(html_doc,

'lxml'

)# 1、獲取所有tr標籤

trs = soup.find_all(

'tr'

)for tr in trs:

print

(tr)

# 2、獲取第2個tr 標籤

tr = soup.find_all(

'tr'

,limit =2)

[1]# 3、獲取所有class等於event的tr標籤

- trs = soup.find_all(

'tr'

,class_ =

'even'

)- trs = soup.find_all(

'tr'

,attrs=

)# 4、將所有id 等於test,class 也等於test的a標籤提取出來

- alist = soup.find_all(

'a',attrs =

)- alist = soup.find_all(

'a',id=

'test'

,class_ =

'test'

)# 5、獲取所有的a標籤的href屬性

hrefs = soup.find_all(

'a')

for a in hrefs:

href = a[

'href'

]# 方式1

href = a.get(

'href'

)# 方式2

href = a.attrs[

'href'

]# 方式3

# 6、獲取純文字資訊

trs = soup.find_all(

'tr')[

1:]for tr in trs:

# 獲取

tds = tr.find_all(

'td'

) title = tds[0]

print

(title.string)

# 方式1

# 獲取tr標籤的所有文字

infos =

list

(tr.strings)

print

(infos)

# 去除空格取文字

infos =

list(tr.stripped_strings)

print

(infos)

import requests

from bs4 import beautifulsoup

url =

''new_url =

''header =

response = requests.get(url,headers =header)

response.encoding =

'utf-8'

html = response.text

soup = beautifulsoup(html,

'lxml'

)conmidtab = soup.find(

'div'

,attrs=

)tables = conmidtab.find_all(

'table'

)for table in tables:

trs = table.find_all(

'tr')[

2:]for index,tr in

enumerate

(trs)

: tds = tr.find_all(

'td'

)if index ==0:

city_td = tds[1]

else

: city_td = tds[0]

temp_td = tds[-2

] city =

list

(city_td.stripped_strings)[0

] temp =

list

(temp_td.stripped_strings)[0

]print

(city,temp)

python 網路爬蟲 beautifulsoup

1.安裝beautifulsoup 2.使用beautifulsoup快速建立 格式 from bs4 import beautifulsoup html 名字 年齡 性別 地點小一 28 北京 soup beatifulsoup html print soup.prettify 3.使用beaut...

爬蟲處理資料的方式(三)BeautifulSoup

使用beautifulsoup提取資料 from bs4 import beautifulsoup html html soup beautifulsoup html,lxml 建立乙個物件,接受html和解析方式 soup.a 拿到a標籤所有的內容,包括 soup.a.string 拿到a標籤裡面...

從零開始學網路爬蟲之BeautifulSoap

之前我們介紹了正規表示式,可能有的小夥伴也對寫正規表示式的用法還不夠熟練,沒關係,我們還有乙個更強大的工具,叫beautiful soup,它可以與requests配合使用,在獲得網頁原始碼後進行分析,實在是很方便。這一節就讓我們一就一起來學習一下beautiful soup。beautiful s...