使用BeautifulSoup抓取文章:抓取所有<p>标签

1 投票
1 回答
1974 浏览
提问于 2025-04-17 21:14

我写了一个脚本,可以从文章中提取段落并把它们写入一个文件。不过,对于某些文章,它并没有提取每一个段落。这让我有点困惑。希望能得到一些指导。我还附上了一个特定文章的链接,在这篇文章中,它没有提取到所有信息。它只提取到第一个引用的句子之前的内容。

链接: http://www.reuters.com/article/2014/03/06/us-syria-crisis-assad-insight-idUSBREA250SD20140306

# Ask user to enter URL
url = raw_input("Please enter a valid URL: ")

# Open txt document for output
txt = open('ctp_output.txt', 'w')

# Parse HTML of article
soup = BeautifulSoup(urllib2.urlopen(url).read())

# retrieve all of the paragraph tags
tags = soup('p')
for tag in tags:
    txt.write(tag.get_text() + '\n' + '\n')

相关问题:

1 个回答

1

这是我用的有效方法:

import urllib2
from bs4 import BeautifulSoup

url = "http://www.reuters.com/article/2014/03/06/us-syria-crisis-assad-insight-idUSBREA250SD20140306"

soup = BeautifulSoup(urllib2.urlopen(url))

with open('ctp_output.txt', 'w') as f:
    for tag in soup.find_all('p'):
        f.write(tag.text.encode('utf-8') + '\n')

注意,在处理文件时,应该使用 with 上下文管理器。还有,你可以直接把 urllib2.urlopen(url) 传给 BeautifulSoup 的构造函数,因为 urlopen 返回的是一个类似文件的对象。

希望这能帮到你。

撰写回答