2017-02-07 40 views
0

这是我正在使用的代码。它返回一个空列表。可以弄清楚我做错了什么!Web报废 - 使用python从页面提取数据

from urllib request import urlopen 
import re 

url = 'http://pubs.acs.org/doi/full/10.1021/jacs.6b10998'# example of a web page 
html = urlopen(url).read().decode('utf-8')# decoding 

cite_year='<span class="citation_year">(.+?)</span>'# extract citation year 
pattern = re.compile(cite_year) #compile 
citation_year = re.findall(pattern, html) #store data into a variable 

print(citation_year)# and print 
+0

你确定你的正则表达式是正确的? –

+0

暗示与样本数据替换的前两行(I做HTML = “” “<跨度类=” citation_year “>测试 ... ... <跨度类=” citation_year“>巴 ...的 ... ... 酒吧 “”” ,然后你的代码的其余部分和预期一样......这会允许你分类问题出在哪里,以及数据是否有像你期望的那样的引号等。还要注意,SO往往不鼓励用正则表达式解析HTML – Foon

回答

0

添加头的要求,我用requestsbs4库:

import requests 
import bs4 
headers = {'User-Agent':'Mozilla/5.0'} 
url = 'http://pubs.acs.org/doi/full/10.1021/jacs.6b10998'# example of a web page 
html = requests.get(url, headers=headers) 
soup = bs4.BeautifulSoup(html.text, 'lxml') 
year = soup.find(class_="citation_year").text 
print(year)