2015-11-03 44 views
1

解析在BeautifulSoup,版本BS4文檔http://www.crummy.com/software/BeautifulSoup/bs4/doc/使用BeautifulSoup通過ID

HTML文檔中列出:

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 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> 
""" 

我們經常使用提取的所有鏈接,例如

for link in soup.find_all('a'): 
    print(link.get('href')) 

輸出

http://example.com/elsie 
http://example.com/lacie 
http://example.com/tillie 

在HTML文檔本身,這些鏈路都在班 「姐」,並與id標籤上市,

<a class="sister" href="http://example.com/elsie" id="link1"> 
<a class="sister" href="http://example.com/lacie" id="link2"> 
<a class="sister" href="http://example.com/tillie" id="link3"> 

在實際的網站,我注意到這些id標籤通常是一個數字列表,例如id="1"。有沒有辦法單獨使用id標籤解析HTML文檔?什麼是最好的方式來做到這一點?

首先,你可以得到一流的 「姐妹」 中的所有標籤,即

soup.find_all(class_="sister") 

然後呢?

回答

1

如果你有find_all()來解決這個問題,你可以使用一個正則表達式或功能

soup.find_all("a", id=re.compile(r"^link\d+$") # id starts with 'link' followed by one or more digits at the end of the value 
soup.find_all("a", id=lambda value: value and value.startswith("link")) # id starts with 'link' 

或者,你可以用一個CSS選擇器來解決:

soup.select("a[id^=link]") # id starts with 'link' 
+0

@alexce我遇到的一個問題是,如果我使用正則表達式,它將返回以正則表達式開頭的所有ID。 假設我只想找到一個特定的鏈接link3。我做了多少? soup.find_all(「a」,id = re.compile(r「^ link \ d + $」)返回以「link」開頭的所有內容 – ShanZhengYang

+0

@ ShanZhengYang,如果你只需要'link3',就不需要正則表達式:'soup.find_all(「a」,id =「link3」)'。 – alecxe

+0

@alexce當然,或'soup.find_all(id =「link3」)'。 – ShanZhengYang