Python 使用Beautifulsoup从右滚动条获取新闻数据
我正在使用以下网页 从右侧滚动条获取数据 我已附上屏幕截图,其中有一个红色箭头标记该段 我使用了以下代码:Python 使用Beautifulsoup从右滚动条获取新闻数据,python,beautifulsoup,urllib2,Python,Beautifulsoup,Urllib2,我正在使用以下网页 从右侧滚动条获取数据 我已附上屏幕截图,其中有一个红色箭头标记该段 我使用了以下代码: def parse(): mainPage = urllib2.urlopen("https://www.google.com/finance?q=NYSE%3AF&ei=LvflU_itN8zbkgW0i4GABQ") lSoupPage = BeautifulSoup(mainPage) for index in lSoupPage.findAll(
def parse():
mainPage = urllib2.urlopen("https://www.google.com/finance?q=NYSE%3AF&ei=LvflU_itN8zbkgW0i4GABQ")
lSoupPage = BeautifulSoup(mainPage)
for index in lSoupPage.findAll("div", {"class" : "jfk-scrollbar"}):
for item in index.findAll("div", {"class" : "news-item"}):
print item.a.text.strip()
我无法通过执行此操作获取新闻url。请帮忙 侧边栏是通过AJAX加载的,不是页面本身的一部分 该页面具有一个内容id:
cid = lSoupPage.find('link', rel='canonical')['href'].rpartition('=')[-1]
使用此选项获取新闻数据:
newsdata = urllib2.urlopen('https://www.google.com/finance/kd?output=json&keydevs=1&recnews=0&cid=' + cid)
不幸的是,返回的数据不是有效的JSON;这些键没有使用引号。它是有效的ECMAScript,但不是有效的JSON
您可以通过使用正则表达式来“修复”,或者使用接受ECMAscript对象表示法的宽松解析器
后者可通过外部设备完成:
使用正则表达式修复:
import re
import json
repaired_data = re.sub(r'(?<={|,)\s*(\w+)(?=:)', r'"\1"', broken_data)
data = json.loads(repaired_data)
重新导入
导入json
修复了_data=re.sub(r'(?该数据是通过AJAX加载的,您在加载的页面源中找不到它。包含该侧边栏的数据。@Martijn Pieters:您是如何获得此链接的?通过查看Chrome developer tools中的网络选项卡,在XHR(AJAX)上进行过滤的请求,然后查看哪个可能包含数据。数据不是有效的JSON,顺便说一句,您需要使用EcmaScript容错解析器而不是JSON
模块,或者使用正则表达式“修复”该响应中的键引用。
import re
import json
repaired_data = re.sub(r'(?<={|,)\s*(\w+)(?=:)', r'"\1"', broken_data)
data = json.loads(repaired_data)