You need to enable JavaScript to run this app. 如何使用BeautifulSoup抓取指定网页第四章国家列表并解决p标签提取问题
优惠活动
大模型
产品
解决方案
定价
更多

如何使用BeautifulSoup抓取指定网页第四章国家列表并解决p标签提取问题

代码调整方案

你当前代码仅定位到了第四章的标题节点,没有获取该标题之后对应的国家列表内容。该网页结构中第四章标题后紧邻的class="report__content"div容器内的

标签即为所有国家条目,调整后的完整代码如下:

from urllib.request import Request, urlopen
from bs4 import BeautifulSoup

# 发起页面请求
reqUS = Request('https://www.state.gov/reports/country-reports-on-terrorism-2019/', headers={'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36'})
US = urlopen(reqUS).read()

# 初始化BeautifulSoup对象
soup = BeautifulSoup(US, 'html.parser')

# 定位第四章标题节点
chapter4_title = soup.find('h2', id="report-toc__section-7")
# 获取标题后紧邻的内容容器
chapter4_content = chapter4_title.find_next_sibling('div', class_="report__content")
# 提取所有p标签的非空文本,得到国家列表
country_list = [p.get_text(strip=True) for p in chapter4_content.find_all('p') if p.get_text(strip=True)]

# 打印结果
print("第四章国家列表:")
for country in country_list:
    print(country)

调整说明

  • 使用find_next_sibling方法定位标题对应的内容区域,避免匹配到其他无关节点
  • 遍历内容区域内的所有

    标签,过滤空文本后即可得到完整的国家列表

  • 若需要清洗国家名称的特殊字符,可直接对country_list内的元素做字符串处理即可

内容的提问来源于stack exchange,提问作者Hasophie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.09 06:03:03