開篇
基本庫requests,bs4
r = requests.get(url)#鏈接url,獲取html
soup = BeautifulSoup(r.text, 'html.parser')
解析器
BeautifulSoup(r.text, 'html.parser')
html.parser就是解析器,主要的解析器有以下幾種:
bs4的html解析器——html.parser
lxml的html解析器——lxml
lxml的xml解析器——xml
html5lib的解析器——html5lib
Tag標(biāo)簽組成? ? ?
<a src=“china_map.jpg” size=“10”>…</a>
a——name,名稱,tag.name
src=“china_map.jpg” size=“10”——Attribute,屬性,tag.attrs
...——NavigableString,非屬性字符串,tag.string
——Commebt,字符串的注釋,獲取方式同上
內(nèi)容遍歷
contents——子節(jié)點(diǎn),遍歷所有子節(jié)點(diǎn)存入列表
children——子節(jié)點(diǎn),迭代類型
descendants——子孫節(jié)點(diǎn),迭代類型
parent——父節(jié)點(diǎn)
parents——先輩節(jié)點(diǎn),迭代類型
通過實(shí)例學(xué)習(xí)如何搭建python爬蟲,目前利用BeautifulSoup、requests模塊,實(shí)現(xiàn)基本爬取操作。
由于爬取的網(wǎng)頁不使用utf-8編碼,所以爬取后漢字顯示為亂碼,需要轉(zhuǎn)碼操作。
code = r.encoding? ?#獲取爬取網(wǎng)頁的編碼信息
r = r.text.encode(code).decode('utf-8')? ?#轉(zhuǎn)碼操作
下一步需要通過正則獲取所需信息,待續(xù)。。。