Skip to main content
 首页 » 编程设计

python之使用 BeautifulSoup4 抓取网页

2025年05月04日23sxdcgaq8080

我正在尝试使用 BeautifulSoup4 打印新闻文章的内容。

网址是:Link

我的当前代码如下,它给出了所需的输出:

page = requests.get('http://www.thehindu.com/news/national/People-showing-monumental-patience-queuing-up-for-a-better-India-says-Venkaiah/article16447029.ece') 
soup = BeautifulSoup(page.content, 'html.parser') 
 
 
article_text = "" 
table = soup.find_all("div",{ "id": "content-body-14266949-16447029"})                               
 
for element in table: 
    article_text += ''.join(element.find_all(text = True)) + "\n\n" 
 
print(article_text) 

但是,问题是我想抓取多个页面,每个页面都有不同的内容正文编号,格式为 xxxxxxxx-xxxxxxxx(2 个 8 位数字 block 。)

我尝试用正则表达式替换 soup.find_all 命令:

table = soup.find_all(text=re.compile("content-body-........-........"))

但这给出了一个错误:

AttributeError: 'NavigableString' object has no attribute 'find_all'

谁能指导我需要做什么?

谢谢。

请您参考如下方法:

正则表达式应该没问题!尝试

table = soup.find_all("div",{ "id": re.compile('content-body-*')})