【问题标题】:How to find all a tags with aria-label attribute BeautifulSoup如何找到所有带有 aria-label 属性 BeautifulSoup 的标签
【发布时间】:2021-10-07 11:37:56
【问题描述】:

我正在尝试使用 Beautiful Soup 来查找所有具有 aria-label 属性的标签(而不是尝试查找具有该属性的任何特定值的标签,只是通常具有该属性的每个标签)。我的代码如下所示。当我运行代码时,我收到一个错误,指出无法解析 aria-label 参数。我怎样才能正确地做到这一点?

url = 'https://www.encodeproject.org/search/?type=Experiment&control_type!=*&status=released&perturbed=false&assay_title=TF+ChIP-seq&assay_title=Histone+ChIP-seq&replicates.library.biosample.donor.organism.scientific_name=Homo+sapiens&biosample_ontology.term_name=K562&biosample_ontology.term_name=HEK293&biosample_ontology.term_name=MCF-7&biosample_ontology.term_name=HepG2&limit=all'

response = requests.get(url)
soup = BeautifulSoup(response.text, "html.parser")
a_tags = soup.findAll('a', aria-label=True)
for tag in a_tags:
    print(tag.text.strip())

【问题讨论】:

  • 提供的答案解决了您的问题吗?

标签: python web-scraping beautifulsoup


【解决方案1】:

您可以使用 CSS 选择器 a[aria-label],它将选择所有具有 aria-label 属性的 a。

要使用 CSS 选择器,请使用 select() 而不是 find_all():

import requests
from bs4 import BeautifulSoup

url = 'https://www.encodeproject.org/search/?type=Experiment&control_type!=*&status=released&perturbed=false&assay_title=TF+ChIP-seq&assay_title=Histone+ChIP-seq&replicates.library.biosample.donor.organism.scientific_name=Homo+sapiens&biosample_ontology.term_name=K562&biosample_ontology.term_name=HEK293&biosample_ontology.term_name=MCF-7&biosample_ontology.term_name=HepG2&limit=all'

response = requests.get(url)
soup = BeautifulSoup(response.text, "html.parser")
a_tags = soup.select('a[aria-label]')
for tag in a_tags:
    print(tag.text.strip())

或者:使用attr= 参数:

a_tags = soup.findAll('a', attrs={"aria-label": True})

或者:检查aria-label是否在.attrs中:

a_tags = soup.findAll(lambda tag: tag.name == "a" and "aria-label" in tag.attrs)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-02-11
    • 2018-08-18
    • 2019-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多