引子:
使用python爬蟲對爬取網頁進行解析的時候,如果使用正則表達式,有很多局限,比如標簽中出現換行,或者標簽的格式不規范,都有可能出現取不到數據,BeautifulSoup作為一個專門處理html格式的python第三方庫,在格式處理上要明顯優與正則表達式,而且使用簡便。
安裝:
下載beautifulsoup4-4.5.0,打開cmd,進入beautifulsoup文件目錄,執行python setup.py install 進行安裝
打開python命令行,執行from bs4 import BeautifulSoup 成功,則安裝成功
使用:
獲取指定標簽及內容
soup=BeautifulSoup(text,"html.parser") ?#text為html文本,"html.parser"指按html格式進行解析
li= soup.find_all(name="li",attrs={"class":"rlbh"}) #查找所有li標簽,class類型為rlbh
find只返回第一個標簽,find_all返回所有標簽,findAll是beautifulsoup3 的方法,在bs4中也可以用,find_all是bs4中的方法。
find_all返回結果為list類型,如果需要在返回結果中繼續匹配可以這樣:
li= soup.find_all(name="li",attrs={"class":"rlbh"})
for i in li:
#get count
lbdj=i.find_all(name="span",attrs={"class":"lbdj"}) ?#匹配li結果中的所有span標簽,且class類型為lbdj
獲取鏈接
a=span[0].find_all(name="a",attrs={"target":"_blank"}) ?#獲取a標簽
href=a[0].get('href') ?#獲取a標簽中href屬性的內容
也可以直接a[0]['href'] 獲取
獲取內容
title=a[0].getText() ?#獲取a標簽中的文本
如:<a href="http:127.0.0.1">localhost</a>獲取到的就是localhost
??