您好,登錄后才能下訂單哦!
https://www.crummy.com/software/BeautifulSoup/bs4/doc.zh/#id4
中文版BeautifulSoup庫
作用
提取HTML和XML文檔中的數據
修改、導航、查找文檔
創建html_doc
>>> html_doc = """
... <html><head><title>The Dormouse's story</title></head>
... <body>
... <p class="title"><b>The Dormouse's story</b></p>
...
... <p class="story">Once upon a time there were three little sisters; and their names were
... <a class="sister" id="link1">Elsie</a>,
... <a class="sister" id="link2">Lacie</a> and
... <a class="sister" id="link3">Tillie</a>;
... and they lived at the bottom of a well.</p>
...
... <p class="story">...</p>
... """
#使用bs4庫
>>> from bs4 import BeautifulSoup
>>> soup = BeautifulSoup(html_doc)
>>> print soup.prettify()
<html>
<head>
<title>
The Dormouse's story
</title>
</head>
<body>
<p class="title">
<b>
The Dormouse's story
</b>
</p>
<p class="story">
Once upon a time there were three little sisters; and their names were
<a class="sister" id="link1">
Elsie
</a>
,
<a class="sister" id="link2">
Lacie
</a>
and
<a class="sister" id="link3">
Tillie
</a>
;
and they lived at the bottom of a well.
</p>
<p class="story">
...
</p>
</body>
</html>
提取所需的字段
>>> soup.title #提取標題
<title>The Dormouse's story</title>
>>> soup.title.name
'title'
>>> soup.title.string #提取標題的內容
u"The Dormouse's story"
>>> soup.a #提取<a>字段信息(第一個<a>)
<a class="sister" id="link1">Elsie</a>
>>> soup.p
<p class="title"><b>The Dormouse's story</b></p>
>>> soup.p['class']
['title']
查找<a>
>>> soup.find_all('a')
[<a class="sister" id="link1">Elsie</a>, <a class="sister" id="link2">Lacie</a>, <a class="sister" id="link3">Tillie</a>]
>>> for link in soup.find_all('a'):
... print link.get('href') #提取link, href字段
...
http://example.com/elsie
http://example.com/lacie
http://example.com/tillie
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。