我使用正则表达式和美丽的汤来从文章中获取信息。我目前似乎无法从输出中得到我所需要的。对于日期,我只需要获取列表中返回的第一个实例。我尝试了遍历列表,但还没有太多运气。对于作者而言,我想剪出一个href标签,只是取得它的名字而不是整个返回的字符串。我尝试了一个循环并更改了一些正则表达式调用,但一直无法缩小范围。任何指导将不胜感激。下面是相关代码:使用正则表达式从文章中获取信息
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')
你根本不需要regex,使用BeautifulSoup!并且日期位于url的最后8个字符中。 –
你能提供一个例子说明如何使用bs4抓取作者吗?我读过美丽的汤文件,他们的方法没有产生所需的输出。尽管我对python很陌生,所以很可能是我的一个误解。 – user3285763