使用python在分页的表中刮取数据
我正在谷歌金融的历史页面上搜寻一只股票的数据() 我可以在当前页面上刮取30行。我面临的问题是,我无法浏览表中的其余数据(31-241行)。如何转到下一页或链接。 以下是我的代码:使用python在分页的表中刮取数据,python,beautifulsoup,screen-scraping,Python,Beautifulsoup,Screen Scraping,我正在谷歌金融的历史页面上搜寻一只股票的数据() 我可以在当前页面上刮取30行。我面临的问题是,我无法浏览表中的其余数据(31-241行)。如何转到下一页或链接。 以下是我的代码: import urllib2 import xlwt #to write into excel spreadsheet from bs4 import BeautifulSoup # Main Coding Section stock_links = open('stock_link_list.txt', 'r'
import urllib2
import xlwt #to write into excel spreadsheet
from bs4 import BeautifulSoup
# Main Coding Section
stock_links = open('stock_link_list.txt', 'r') #opening text file for reading
#url="https://www.google.com/finance/historical?q=NSE%3ASIEMENS&ei=zHXOVLPnApG2iALxxYCADQ"
for url in stock_links:
OurFile = urllib2.urlopen(url)
OurHtml = OurFile.read()
OurFile.close()
soup = BeautifulSoup(OurHtml)
#soup1 = soup.find("div", {"class": "gf-table-wrapper sfe-break-bottom-16"}).get_text()
soup1 = soup.find("table", {"class": "gf-table historical_price"}).get_text()
end = url.index('&')
filename = url[47:end]
file = open(filename, 'w') #opening text file for writing
file.write(soup1)
#file.write(soup1.get_text()) #writing to the text file
file.close() #closing the text file
您必须对其进行微调,我会捕捉到更具体的错误,但您可以不断增加
start
以获取下一个数据:
url = "https://www.google.com/finance/historical?q=NSE%3ASIEMENS&ei=W8LUVLHnAoOswAOFs4DACg&start={}&num=30"
from bs4 import BeautifulSoup
import requests
# Main Coding Sectio
start = 0
while True:
try:
nxt = url.format(start)
r = requests.get(nxt)
soup = BeautifulSoup(r.content)
print(soup.find("table",{"class": "gf-table historical_price"}).get_text())
except Exception as e:
print(e)
break
start += 30
这将获取截至最后日期2月7日的所有表格数据:
......
Date
Open
High
Low
Close
Volume
Feb 7, 2014
552.60
557.90
548.25
551.50
119,711
乍一看,
行限制
选项允许每页最多显示30行,但我手动将查询字符串参数改为更大的数字,并意识到每页最多可以查看200行
将URL更改为
https://www.google.com/finance/historical?q=NSE%3ASIEMENS&ei=OM3UVLFtkLnzBsjIgYAI&start=0&num=200
它将显示200行
然后更改start=200&num=400
但更符合逻辑的是,如果你有很多其他的sunch链接
然后你可以刮去分页区域,最后一个TR,抓取下一页的链接,刮去谢谢Padraic C。你的回答今天帮我学到了一些新东西。我在现有链接列表中追加了“&start={}”。它就像一个符咒。我无法推翻你的答案,因为我缺乏声望。有一天我拿到分数,我会来这里投票给这个很棒的答案。@NitheshKHP,不用担心。谢谢Umair。我确实在你的建议后使用了url,帮助我改进了代码。