我用regex和beautiful soup从一篇文章中获取信息。我目前似乎无法从输出中得到我所需要的。对于日期,我只需要获取列表中返回的第一个实例。我试着反复浏览这个列表,但还没有什么好运气。对于作者来说,我想去掉a href标签,只想知道是谁写的,而不是整个返回的字符串。我尝试了一个循环并更改了一些regex调用,但未能缩小范围。任何指导都将不胜感激。以下是相关代码:
import urllib2
from bs4 import BeautifulSoup
import re
from time import *
url: http://www.reuters.com/article/2014/02/26/us-afghanistan-usa-militants-idUSBREA1O1SV20140226
# Parse HTML of article, aka making soup
soup = BeautifulSoup(urllib2.urlopen(url).read())
# Write the article author to the file
regex = '<p class="byline">(.+?)</p>'
pattern = re.compile(regex)
byline = re.findall(pattern,str(soup))
txt.write("Author: " + str(byline) + '\n' + '\n')
# Write the article date to the file
regex = '<span class="timestamp">(.+?)</span>'
pattern = re.compile(regex)
byline = re.findall(pattern,str(soup))
txt.write("Date: " + str(byline) + '\n' + '\n')
您可以使用BeautifulSoup来准确地获取您所需要的内容,方法与您描述的几乎相同,只是没有regex。因为您知道您感兴趣的标记的特征,所以可以直接使用bs4的
find
来搜索它们更新: 如果您将整个内容包装在
try/except
结构中,您可以解决缺少署名的情况,并定义应该发生的一些替代操作。你知道吗相关问题 更多 >
编程相关推荐