Python安全筆記(一)
阿新 • • 發佈:2018-12-30
BeatifulSoup用法
1、BeatifulSoup安裝
BeatifulSoup是常用的Python的擴充套件包,用於對web檔案格式化顯示、按條件查詢等功能。它是bs4包中的一部分,使用前需安裝bs4:
pip install bs4
並在python程式中匯入:
from bs4 import BeatifulSoup
2、常用用法:
2.1 對下載的網頁按格式顯示:
r = requests.get("www.baidu.com") cont = r.content soup = BeautifulSoup(doc, "html.parser") print(BeatifulSoup.prettify()) //將html檔案按縮排格式顯示
2.2 對網頁按標籤、按屬性、按內容檢索
例子:
html_doc = ''' <html><head><title>The Dormouse's Story</title></head> <body> <p class="title"><b>The Dormouse's Story</b></p> <asdasd>hello world</asdasd> <p class="story">Once upon a time,there were three little sisters,and their names were <a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>, <a href="http://example.com/lacie" class="sister" id="link2">Lacie</a>and <a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>; and they lived at the bottom of a well.</p> <p class="story"> ...</p> '''
2.2.1 檢索出所有p標籤的內容
1)打印出所有名稱為“P”的標籤,結果可以按列表的方式使用,比如使用index
soup=BeautifulSoup(html_doc, "html.parser")
print(soup.find_all("p"))
2) 打印出所有名稱為“P”的標籤中的第一個
print(soup.find_all("p")[0]
結果為:
<p class="title"><b>The Dormouse's Story</b></p>
3)分行打印出所有名稱為“a”的標籤,
for i in soup.find_all(“a”):
print(i)
結果為
<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>
<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>
<a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>
4)也可以結合正則表示式用,以下返回名稱以p開頭的標籤:
soup.find_all(re.compile("^p")
5)可以根據內容檢索,以下打印出包含id=link2的標籤:
print(soup.find_all(id="link2"))
結果為:
[<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>]
打印出包含"id=link2"的標籤中的href元素:
print(soup.find_all(id="link2")[0]["href"])
結果為:
http://example.com/lacie
6) 可以根據標籤中含的多個元素聯合查詢,以下打印出“id=link2”且“class="sister"的標籤(注意class要寫成class_):
print(soup.find_all(id="link2",class_="sister"))
結果是:
[<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>]