【问题标题】:Extract all Links in Table with Beautiful Soup用 Beautiful Soup 提取表中的所有链接
【发布时间】:2021-03-27 16:37:50
【问题描述】:

<td style="text-align: center;"><a title="Some title" href="https://www.blabla.com">Testing</a></td>

我正在尝试使用BeautifulSoup 来获取所有hrefa 标签,它们是td 标签的子标签。

我可以跑

urls = [x for x in soup.findAll("td")]

获取所有td标签,然后手动循环查看它们是否包含a标签,如果是则提取href,但是有没有更简洁的方法可以在一行中执行此操作?

【问题讨论】:

  • 我想你需要类似的东西links = [link['href'] for link in td.findAll('a') for td in soup.findAll('td')]
  • 试试这个urls = [x['href'] for x in soup.select("td>a")]

标签: python html beautifulsoup html-parsing


【解决方案1】:

尝试使用:has() CSS 选择器选择所有具有<a> 标签的td 标签。

from bs4 import BeautifulSoup

html = """<td style="text-align: center;"><a title="Some title" href="https://www.blabla.com">Testing</a></td>"""
soup = BeautifulSoup(html, "html.parser")
print([tag.find("a")["href"] for tag in soup.select("td:has(a)")])

输出:

['https://www.blabla.com']

【讨论】:

    猜你喜欢
    • 2015-09-18
    • 1970-01-01
    • 2023-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多