如何使用BeautifulSoup查找所有带aria-label属性的a标签
BeautifulSoup筛选带指定属性标签的解决方法
报错原因
你代码报错的核心原因是aria-label属性名包含连字符,无法直接作为findAll/find_all方法的关键字参数传递,Python会将连字符识别为减号运算符,导致参数解析失败。
正确实现方案
方案1:使用attrs参数(官方推荐)
将属性筛选条件放到attrs字典参数中,键为属性名,值设为True即可筛选所有包含该属性的元素,不限制属性的具体取值:
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.find_all('a', attrs={"aria-label": True}) for tag in a_tags: print(tag.text.strip())
方案2:使用CSS选择器(更简洁)
直接调用select方法,用CSS属性选择器语法筛选,写法更直观:
# 仅需替换原代码中的find_all行即可 a_tags = soup.select('a[aria-label]')
内容的提问来源于stack exchange,提问作者Charlie Rettig
相关产品推荐
相关产品推荐

