使用BeautifulSoup解析网页遇阻:如何提取指定字段的单独值?
解决BeautifulSoup提取指定HTML字段的问题
目标HTML结构
<small> <span class="label label-primary">CVE-2019-11198</span> <span class="label label-warning">6.1 - Medium</span> - August 05, 2019 </small>
需要提取的字段:
CVE-2019-11198(CVE编号)6.1(漏洞评分)Medium(漏洞等级)August 05, 2019(漏洞日期)
原代码问题
最初的代码只能获取<small>标签下的全部文本,无法拆分单独字段:
cves=soup.find_all("div", class_="cve_listing") for cve in cves: #CVE, vuln numeric rating, vuln sev cat, vuln date vulninfo=cve.find("small").text
修改后的代码尝试提取单独值,但触发报错:
cves=soup.find_all("div", class_="cve_listing") for cve in cves: vulncve=cve.find("span", class_="label-primary") vulninfo=cve.select_one('span.label').parent vulninfores=[x.get_text(strip=True) for x in vulninfo.contents if len(x.text) > 1]
报错信息:
AttributeError: 'NavigableString' object has no attribute 'text'
报错原因
vulninfo.contents包含了NavigableString类型的文本节点(比如换行符、空格、- August 05, 2019这类纯文本),这类节点没有text属性,直接调用x.text会触发AttributeError。
高效解析方案
方案1:精准定位每个元素(推荐)
通过标签和class直接定位目标元素,拆分字段:
import bs4 cves = soup.find_all("div", class_="cve_listing") for cve in cves: small_tag = cve.find("small") # 提取CVE编号 cve_id = small_tag.find("span", class_="label-primary").get_text(strip=True) # 提取漏洞评分和等级 rating_content = small_tag.find("span", class_="label-warning").get_text(strip=True) numeric_rating, severity = rating_content.split(" - ") # 提取漏洞日期:过滤非标签节点,清理多余字符 date_text = "" for child in small_tag.children: if not isinstance(child, bs4.element.Tag): raw_text = child.strip() if raw_text.startswith("-"): date_text = raw_text.lstrip("- ").strip() break # 输出结果 print(f"CVE编号: {cve_id}, 漏洞评分: {numeric_rating}, 漏洞等级: {severity}, 发布日期: {date_text}")
方案2:利用stripped_strings简化处理
stripped_strings会自动过滤空白字符,返回所有有意义的文本片段,再拆分字段:
cves = soup.find_all("div", class_="cve_listing") for cve in cves: small_tag = cve.find("small") # 获取所有清理后的文本片段 text_segments = [seg for seg in small_tag.stripped_strings] # 拆分对应字段 cve_id = text_segments[0] numeric_rating, severity = text_segments[1].split(" - ") date_text = text_segments[2] # 输出结果 print(f"CVE编号: {cve_id}, 漏洞评分: {numeric_rating}, 漏洞等级: {severity}, 发布日期: {date_text}")
内容的提问来源于stack exchange,提问作者Jshee
相关产品推荐
相关产品推荐

