【问题标题】:BeautifulSoup returns all links, rather than the first linkBeautifulSoup 返回所有链接,而不是第一个链接
【发布时间】:2021-03-13 17:18:27
【问题描述】:
<table>
    <tr>
        <td>
            <a href=""> Text </a>
            <a href=""> Text </a>
        </td>
        <td>
            <a href=""> Text </a>
        </td>
    </tr>
    <tr>
        <a href=""> Text </a>
        </td>
        <td>
        <a href=""> Text </a>
    </tr>
</table>

我想从每个 td 元素中获取第一个链接。我尝试使用以下代码来实现:

website_data.select("tr td a")

但是,这给了我 td 元素内的所有 a 元素。 我怎样才能做到这一点?

【问题讨论】:

  • [i['href'] for i in website_data.select("tr td a")] ?

标签: python beautifulsoup


【解决方案1】:

如果你想要第一个孩子一个标签,那么你可以使用 a:nth-child(1) 来做到这一点

from bs4 import BeautifulSoup as bs

html ='''<html>
    <head></head>
    <body>
        <table>
            <tbody>
                <tr>
                    <td><a href="link1"> Text1 </a> <a href="link2"> Text2 </a></td>
                    <td><a href="link1"> Text1 </a></td>
                </tr>
                <tr>
                    <td><a href="link1"> Text1 </a> <a href="link2"> Text2 </a></td>
                    <td><a href="link1"> Text1 </a></td>
                </tr>
            </tbody>
        </table>
    </body>
</html>
'''

soup = bs(html, 'lxml')
print([(i.text, i['href']) for i in soup.select('td a:nth-child(1)')])

【讨论】:

    【解决方案2】:

    如果 website_dataBeautifulSoup 对象,那么您可以尝试以下操作:

    [td_element.find('a', href=True)['href'] for td_element in website_data.find_all('td')]
    

    【讨论】:

    • 谢谢。明天我会试试这个,当它起作用时,我会接受你的回答
    猜你喜欢
    • 2022-11-19
    • 1970-01-01
    • 2021-12-01
    • 2019-05-12
    • 1970-01-01
    • 1970-01-01
    • 2013-04-08
    • 1970-01-01
    • 2015-10-23
    相关资源
    最近更新 更多