使用BeautifulSoup通过标签属性检索提取行内指定文本
错误原因分析
soup.find_all()返回的是匹配到的元素列表,不能直接对列表调用find()方法,必须遍历列表中的每个元素单独操作。- 你在筛选p标签的属性时,把内部i标签的class属性直接写到了p标签的筛选条件里,BeautifulSoup不会跨元素匹配属性,所以这个筛选条件永远匹配不到结果。
正确实现代码
使用CSS选择器可以更简单直观地完成需求,代码示例如下:
from bs4 import BeautifulSoup # 假设你已经将HTML源码存入html_content变量 soup = BeautifulSoup(html_content, 'html.parser') # 方法1:直接提取所有正确答案 answers = [] # 定位符合条件的i标签,再取父元素p的文本内容 for correct_i in soup.select('p.answer > i.fa.fa-circle'): ans_text = correct_i.parent.get_text(strip=True) answers.append(ans_text) print(answers) # 输出结果:['holy place', 'plays'] # 方法2:按题目块匹配,同时存储题目和对应答案 question_blocks = soup.find_all('div', class_='card card-custom custom-color') qa_pairs = [] for block in question_blocks: # 提取题干 question = block.find('h1', class_='card-header').get_text(strip=True) # 提取该题正确答案 correct_i = block.select_one('p.answer > i.fa.fa-circle') answer = correct_i.parent.get_text(strip=True) if correct_i else '' qa_pairs.append({'question': question, 'answer': answer})
如果解析过程中出现格式问题,可以安装lxml解析库,将代码中的html.parser替换为lxml即可。
内容的提问来源于stack exchange,提问作者Mehady
相关产品推荐
相关产品推荐

