使用regex从arti获取信息

2024-06-18 13:07:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我用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')

Tags: thefromimportreurl列表articleurllib2
1条回答
网友
1楼 · 发布于 2024-06-18 13:07:06

您可以使用BeautifulSoup来准确地获取您所需要的内容,方法与您描述的几乎相同,只是没有regex。因为您知道您感兴趣的标记的特征,所以可以直接使用bs4的find来搜索它们

#make some soup
soup = BeautifulSoup(urllib2.urlopen(url).read())

#extract byline and date text from their respective tags
try:
    byline=soup.find("p", {'class':'byline'}).text
    date=soup.find("span", {'class':'timestamp'}).text
except:
    print 'byline missing!'

更新: 如果您将整个内容包装在try/except结构中,您可以解决缺少署名的情况,并定义应该发生的一些替代操作。你知道吗

相关问题 更多 >