从python中提取特定于html的漂亮标签

2024-06-13 08:44:35 发布

您现在位置:Python中文网/ 问答频道 /正文

从以下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>'

我想得到

^{pr2}$

到目前为止,我有以下代码

soup3=BeautifulSoup(html,'html.parser')
spans=soup3.findAll('tr')
[el.text for el in soup3.find_all('a')]

产生

['[1]', 'Medellín', 'Colombia']

不过,第一个项目也要支持类,我不想要它。在

你能提供线索吗?在

我不想引用列表的第二和第三个位置,因为我不想引用其他htmls的第一个位置([1]0)


Tags: titlehtmlwikieltrclasstdhref
2条回答

您所插入的信息似乎也存在于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']

对于这种代码模式:

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

您可以尝试使用更具体的选择器,例如:

^{pr2}$

或者

soup3=BeautifulSoup(html,'html.parser')
spans=soup3.select('tr')
[el.text for el in spans.find_all('td>a')]

相关问题 更多 >