?
Beautiful Soup庫(kù)解析器 | ||
解析器 |
使用方法 | 條件 |
bs4的HTML解析器 | BeautifulSoup(mk, 'html.parser') | 安裝bs4庫(kù) |
lxml的HTML解析器 |
BeautifulSoup(mk,'xml') | pip install lxml |
lxml的XML解析器 | BeautifulSoup(mk,' xml') | pip install lxml |
html5lib的解析器 | BeautifulSoup(mk,' htm5lib') | pip install htm151ib |
Beautiful Soup的基本元素
Beautiful Soup的基本元素 | |
基本元素 | 說(shuō)明 |
Tag | 標(biāo)簽,最基本的信息組織單元,分別用<>和標(biāo)明開頭和結(jié)尾 |
Name |
標(biāo)簽的名字,<>....
的名字是'p', 格式: |
Attributes |
標(biāo)簽的屬性,字典形式組織,格式:
|
NavigableString |
標(biāo)簽內(nèi)非屬性字符串,<>...中字符串, 格式:
|
Comment | 標(biāo)簽內(nèi)字符串的注釋部分,一種特殊的Comment類型 |
?
import requests
from bs4 import BeautifulSoup
r = requests.get("https://www.python123.io/ws/demo.html")
demo = r.text
soup = BeautifulSoup(demo, 'html.parser')
print soup.a #
Basic Python
print soup.a.name #a
print soup.a.parent.name #p
print soup.a.attrs #{u'href': u'http://www.icourse163.org/course/BIT-268001', u'class': [u'py1'], u'id': u'link1'}
print soup.a.attrs['class'] #[u'py1']
print type(soup.a.attrs) #
print type(soup.a) #
print soup.a.string #Basic Python
print soup.p #
The demo python introduces several python courses.
print soup.p.string #The demo python introduces several python courses.
newsoup = BeautifulSoup("
this is not a comment
", "html.parser")
print newsoup.b.string #this is a comment
print type(newsoup.b.string) #
print newsoup.p.string #this is not a comment
print type(newsoup.p.string) #
?
Beautiful Soup的遍歷方法
?
標(biāo)簽樹的下行遍歷
標(biāo)簽樹的下行遍歷 |
|
屬性 | 說(shuō)明 |
.contents |
子節(jié)點(diǎn)的列表,將
|
.children | 子節(jié)點(diǎn)的選代類型,與.contents類似, 用于循環(huán)遍歷兒子節(jié)點(diǎn) |
.descendants | 子孫節(jié)點(diǎn)的選代類型,包含所有子孫節(jié)點(diǎn),用于循環(huán)遍歷 |
r = requests.get("https://www.python123.io/ws/demo.html")
demo = r.text
soup = BeautifulSoup(demo, 'html.parser')
#down
print soup.head.contents #[
]
print soup.body.contents #[u'\n',
The demo python introduces several python courses.
, u'\n',
Python is a wonderful general-purpose programming language. You can learn Python from novice to professional by tracking the following courses:\r\n
Basic Python
and
Advanced Python
.
, u'\n']
print len(soup.body.contents) #5
for child in soup.body.children: #遍歷兒子節(jié)點(diǎn)
print child
for child in soup.body.descendants: #遍歷子孫節(jié)點(diǎn)
print child
?
標(biāo)簽樹的上行遍歷
屬性 | 說(shuō)明 |
.parent | 節(jié)點(diǎn)的父親標(biāo)簽 |
.parents | 節(jié)點(diǎn)先輩標(biāo)簽的迭代類型,用于循環(huán)遍歷先輩節(jié)點(diǎn) |
?
#up
r = requests.get("https://www.python123.io/ws/demo.html")
demo = r.text
soup = BeautifulSoup(demo, 'html.parser')
print soup.a.parent #
Python is a wonderful general-purpose programming language. You can learn Python from novice to professional by tracking the following courses:
Basic Python
and
Advanced Python
.
for parent in soup.a.parents:
if parent is None:
print parent
else:
print parent.name
#p
#body
#html
#[document]
?
標(biāo)簽樹的平行遍歷(平行遍歷發(fā)生在同一個(gè)父節(jié)點(diǎn)下的各節(jié)點(diǎn)間)
屬性 | 說(shuō)明 |
.next_ sibling | 返回按照HTML文本順序的下一個(gè)平行節(jié)點(diǎn)標(biāo)簽 |
.previous_sibling | 返回按照HTML文本順序的上一 個(gè)平行節(jié)點(diǎn)標(biāo)簽 |
.next_ siblings | 選代類型,返回按照HTML文本順序的后續(xù)所有平行節(jié)點(diǎn)標(biāo)簽 |
.previous siblings | 迭代類型,返回按照HTML文本顧序的前續(xù)所有平行節(jié)點(diǎn)標(biāo)簽 |
r = requests.get("https://www.python123.io/ws/demo.html")
demo = r.text
soup = BeautifulSoup(demo, 'html.parser')
print soup.a.next_sibling # and
print soup.a.next_sibling.next_sibling #
Advanced Python
print soup.a.previous_sibling #Python is a wonderful general-purpose programming language. You can learn Python from novice to professional by tracking the following courses:
for sibling in soup.a.next_sibling: #遍歷后序節(jié)點(diǎn)
print sibling
for sibling in soup.a.previous_sibling: #遍歷前序節(jié)點(diǎn)
print sibling
?
?
基于bs4庫(kù)html的格式化與編碼
r = requests.get("https://www.python123.io/ws/demo.html")
demo = r.text
soup = BeautifulSoup(demo, 'html.parser')
print soup.prettify()
print soup.a.prettify()
?
三種信息標(biāo)記形式的比較
XML |
最早的通用信息標(biāo)記語(yǔ)言,可擴(kuò)展性好,但繁瑣。 |
Internet 上的信息交互與傳遞。 |
JSON |
信息有類型,適合程序處理(js),較XML簡(jiǎn)潔。 |
移動(dòng)應(yīng)用云端和節(jié)點(diǎn)的信息通信,無(wú)注釋。 |
YAML |
信息無(wú)類型,文本信息比例最高,可讀性好。 |
移動(dòng)應(yīng)用云端和節(jié)點(diǎn)的信息通信,無(wú)注釋。 |
?
信息提取的一般方法
方法一:完整解析信息的標(biāo)記形式,再提取關(guān)鍵信息。
XML JSON YAML
需要標(biāo)記解析器
例如: bs4庫(kù) 的標(biāo)簽樹遍歷
優(yōu)點(diǎn):信息解析準(zhǔn)確
缺點(diǎn):提取過程繁瑣,速度慢。
?
方法二:無(wú)視標(biāo)記形式,直接搜索關(guān)鍵信息。
搜索
對(duì)信息的文本查找函數(shù)即可。
優(yōu)點(diǎn):提取過程簡(jiǎn)潔,速度較快。
缺點(diǎn):
提取結(jié)果準(zhǔn)確性與信息內(nèi)容相關(guān)。
?
<> .find_ all(name, attrs, recursive, string,**kwargs) |
|
返回一個(gè)列表類型,存儲(chǔ)查找的結(jié)果。 | |
name | 對(duì)標(biāo)簽名稱的檢索字符串。 |
attrs | 對(duì)標(biāo)簽屬性值的檢索字符串,可標(biāo)注屬性檢索。 |
recursive | 是否對(duì)子孫全部檢索,默認(rèn)True。 |
string | <>...中字符串區(qū)域的檢索字符串。 |
?
r = requests.get("https://www.python123.io/ws/demo.html")
demo = r.text
soup = BeautifulSoup(demo, 'html.parser')
for link in soup.find_all('a'):
print link.get('href')
#http://www.icourse163.org/course/BIT-268001
#http://www.icourse163.org/course/BIT-1001870001
print soup.find_all(['a', 'b']) #[
The demo python introduces several python courses.
,
Basic Python
,
Advanced Python
]
print soup.find_all(id='link1') #找出所有id為link1的字符串
print soup.find_all(True)
import re
soup.find_all(id=re.compile('link')) #找出所有id含有l(wèi)ink的字符串
r = requests.get("https://www.python123.io/ws/demo.html")
demo = r.text
soup = BeautifulSoup(demo, 'html.parser')
print soup.find_all(string = 'Basic Python') #僅找出'Basic Python'字符串
print soup.find_all(string=re.compile('Python')) #找出含有Python的所有字符串
實(shí)例:中國(guó)大學(xué)排名定向爬蟲
def gethtmltext(url):
try:
r = requests.get(url, timeout=30)
r.raise_for_status()
r.encoding = r.apparent_encoding
print r.text
return r.text
except:
print "error"
return ""
def fillunivlist(ulist, html):
soup = BeautifulSoup(html, 'html.parser')
for tr in soup.find('tbody').children:
if isinstance(tr, bs4.element.Tag):
print tr
tds = tr('td')
ulist.append([tds[0].string, tds[1].string])
def printunivlist(ulist, num):
print "{:^10}\t{:^6}\t{:^10}".format("排名", "學(xué)校", "總分")
for i in range(num):
u = ulist[i]
print "{:^10}\t{:^6}\t{:^10}".format(u[0], u[1], u[2])
def main():
uinfo = []
url = 'http://www.zuihaodaxue.com/zuihaodaxuepaiming2016.html'
html = gethtmltext(url)
fillunivlist(uinfo, html)
printunivlist(uinfo, 20)
if __name__ == "__main__":
main()
?
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號(hào)聯(lián)系: 360901061
您的支持是博主寫作最大的動(dòng)力,如果您喜歡我的文章,感覺我的文章對(duì)您有幫助,請(qǐng)用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長(zhǎng)非常感激您!手機(jī)微信長(zhǎng)按不能支付解決辦法:請(qǐng)將微信支付二維碼保存到相冊(cè),切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對(duì)您有幫助就好】元
