?
Beautiful Soup庫解析器 | ||
解析器 |
使用方法 | 條件 |
bs4的HTML解析器 | BeautifulSoup(mk, 'html.parser') | 安裝bs4庫 |
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的基本元素 | |
基本元素 | 說明 |
Tag | 標簽,最基本的信息組織單元,分別用<>和標明開頭和結尾 |
Name |
標簽的名字,<>....
的名字是'p', 格式: |
Attributes |
標簽的屬性,字典形式組織,格式:
|
NavigableString |
標簽內非屬性字符串,<>...中字符串, 格式:
|
Comment | 標簽內字符串的注釋部分,一種特殊的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的遍歷方法
?
標簽樹的下行遍歷
標簽樹的下行遍歷 |
|
屬性 | 說明 |
.contents |
子節點的列表,將
|
.children | 子節點的選代類型,與.contents類似, 用于循環遍歷兒子節點 |
.descendants | 子孫節點的選代類型,包含所有子孫節點,用于循環遍歷 |
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: #遍歷兒子節點
print child
for child in soup.body.descendants: #遍歷子孫節點
print child
?
標簽樹的上行遍歷
屬性 | 說明 |
.parent | 節點的父親標簽 |
.parents | 節點先輩標簽的迭代類型,用于循環遍歷先輩節點 |
?
#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]
?
標簽樹的平行遍歷(平行遍歷發生在同一個父節點下的各節點間)
屬性 | 說明 |
.next_ sibling | 返回按照HTML文本順序的下一個平行節點標簽 |
.previous_sibling | 返回按照HTML文本順序的上一 個平行節點標簽 |
.next_ siblings | 選代類型,返回按照HTML文本順序的后續所有平行節點標簽 |
.previous siblings | 迭代類型,返回按照HTML文本顧序的前續所有平行節點標簽 |
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: #遍歷后序節點
print sibling
for sibling in soup.a.previous_sibling: #遍歷前序節點
print sibling
?
?
基于bs4庫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()
?
三種信息標記形式的比較
XML |
最早的通用信息標記語言,可擴展性好,但繁瑣。 |
Internet 上的信息交互與傳遞。 |
JSON |
信息有類型,適合程序處理(js),較XML簡潔。 |
移動應用云端和節點的信息通信,無注釋。 |
YAML |
信息無類型,文本信息比例最高,可讀性好。 |
移動應用云端和節點的信息通信,無注釋。 |
?
信息提取的一般方法
方法一:完整解析信息的標記形式,再提取關鍵信息。
XML JSON YAML
需要標記解析器
例如: bs4庫 的標簽樹遍歷
優點:信息解析準確
缺點:提取過程繁瑣,速度慢。
?
方法二:無視標記形式,直接搜索關鍵信息。
搜索
對信息的文本查找函數即可。
優點:提取過程簡潔,速度較快。
缺點:
提取結果準確性與信息內容相關。
?
<> .find_ all(name, attrs, recursive, string,**kwargs) |
|
返回一個列表類型,存儲查找的結果。 | |
name | 對標簽名稱的檢索字符串。 |
attrs | 對標簽屬性值的檢索字符串,可標注屬性檢索。 |
recursive | 是否對子孫全部檢索,默認True。 |
string | <>...中字符串區域的檢索字符串。 |
?
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含有link的字符串
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的所有字符串
實例:中國大學排名定向爬蟲
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("排名", "學校", "總分")
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()
?
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

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