2017-02-03 36 views
0

獲得源代碼後的關鍵字,我有Beautifulsoup搜索在ATTRS

[<div amy="sister" tommy="brother" julie="link1">E11</div>] 
[<div amy="sister" tommy="brother" julie="link2_cat">E12</div>] 
[<div amy="sister" tommy="brother" julie="link3_cat">E13</div>] 

我想提取的那些包含「_cat」朱莉。我怎麼用find_all(attr)來做到這一點?

我嘗試

soup.find_all('div',{"julie":re.compile("_cat")}) 

但不工作

回答

1
import bs4 

html = '''<div amy="sister" tommy="brother" julie="link1">E11</div> 
<div amy="sister" tommy="brother" julie="link2_cat">E12</div> 
<div amy="sister" tommy="brother" julie="link3_cat">E13</div>''' 
soup = bs4.BeautifulSoup(html, 'lxml') 

soup.find_all('div',{"julie":re.compile("_cat")}) 

出來:

[<div amy="sister" julie="link2_cat" tommy="brother">E12</div>, 
<div amy="sister" julie="link3_cat" tommy="brother">E13</div>] 

你應該soup對象使用find_all(),而不是在標籤的列表。

1

如果你的意思去的julie標籤的屬性值,treat each matched tag as a dictionary

In [5]: [tag["julie"] for tag in soup.find_all('div',{"julie":re.compile("_cat")})] 
Out[5]: ['link2_cat', 'link3_cat'] 

還有一種更簡潔的方式來匹配所需的元素 - CSS selectors

In [6]: [tag["julie"] for tag in soup.select('div[julie$=_cat]')] 
Out[6]: ['link2_cat', 'link3_cat'] 

$=選擇裝置「以。。結束」。