[英]extract specific tags from html using python beautiful soup
從下面的html
html='<tr><th scope="row">Born</th><td><span style="display:none"> (<span class="bday">1994-01-28</span>) </span>28 January 1994<span class="noprint ForceAgeToShow"> (age 23)</span><sup class="reference" id="cite_ref-buenamusica_1-0"><a href="#cite_note-buenamusica-1">[1]</a></sup><br/><a href="/wiki/Medell%C3%ADn" title="Medellín">Medellín</a>, <a href="/wiki/Colombia" title="Colombia">Colombia</a></td></tr>'
我想得到
['Medellin','Colombia']
到目前為止,我有以下代碼
soup3=BeautifulSoup(html,'html.parser')
spans=soup3.findAll('tr')
[el.text for el in soup3.find_all('a')]
哪個產生
['[1]', 'Medellín', 'Colombia']
但是,也是上課的第一項,我不想要。
你能提供線索嗎?
我不想引用列表的第二和第三位置,因為我不希望其他html都具有第一位置([1] 0
對於這種代碼模式:
<tr>
<th scope="row">Born</th>
<td>
<span style="display:none"> (<span class="bday">1994-01-28</span>) </span>
28 January 1994
<span class="noprint ForceAgeToShow"> (age 23)</span>
<sup class="reference" id="cite_ref-buenamusica_1-0">
<a href="#cite_note-buenamusica-1">[1]</a>
</sup>
<br/>
<a href="/wiki/Medell%C3%ADn" title="Medellín">Medellín</a>,
<a href="/wiki/Colombia" title="Colombia">Colombia</a>
</td>
</tr>
您可以嘗試使用更具體的選擇器,例如:
soup3=BeautifulSoup(html,'html.parser')
spans=soup3.select('tr>td>a')
[el.text for el in spans]
要么
soup3=BeautifulSoup(html,'html.parser')
spans=soup3.select('tr')
[el.text for el in spans.find_all('td>a')]
您感興趣的信息似乎也出現在title
屬性中。 您可以嘗試使用它來代替text
並丟棄它為None
的條目。
from bs4 import BeautifulSoup
html='<tr><th scope="row">Born</th><td><span style="display:none"> (<span class="bday">1994-01-28</span>) </span>28 January 1994<span class="noprint ForceAgeToShow"> (age 23)</span><sup class="reference" id="cite_ref-buenamusica_1-0"><a href="#cite_note-buenamusica-1">[1]</a></sup><br/><a href="/wiki/Medell%C3%ADn" title="Medellín">Medellín</a>, <a href="/wiki/Colombia" title="Colombia">Colombia</a></td></tr>'
soup3=BeautifulSoup(html,'html.parser')
spans=soup3.findAll('tr')
[el.get('title') for el in soup3.find_all('a') if el.get('title') is not None]
# ['Medellín', 'Colombia']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.