【问题标题】:Scraping data through paginated table using python使用python通过分页表抓取数据
【发布时间】:2015-04-06 15:43:06
【问题描述】:

我正在通过谷歌财经的历史页面抓取股票的数据 (http://www.google.com/finance/historical?q=NSE%3ASIEMENS&ei=PLfUVIDTDuSRiQKhwYGQBQ)。

我可以抓取当前页面上的 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')  #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

【问题讨论】:

    标签: python beautifulsoup screen-scraping


    【解决方案1】:

    您必须对其进行微调,我会发现更具体的错误,但您可以继续增加 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
    

    【讨论】:

    • 谢谢 Padraic C。您的回答帮助我今天学到了一些新东西。我将“&start={}”附加到我现有的链接列表中。它就像一个魅力。由于我缺乏声誉积分,我无法支持您的回答。我有积分的那一天,我会来这里并为这个很棒的答案投票。
    • @NitheshKHP,不用担心。
    【解决方案2】:

    乍一看,Row Limit 选项允许每页最多显示 30 行,但我手动将查询字符串参数更改为更大的数字,并意识到我们每页最多可以查看 200 行

    把网址改成

    https://www.google.com/finance/historical?q=NSE%3ASIEMENS&ei=OM3UVLFtkLnzBsjIgYAI&start=0&num=200

    它将显示 200 行

    然后改start=200&num=400

    但更合乎逻辑的是,如果您有许多其他类型的链接。

    然后你就可以抓取Pagination区域,最后一个TR,抓取下一页的那些链接,然后抓取

    【讨论】:

    • 感谢 Umair。根据您的建议,我确实使用了 url,帮助我改进了我的代码。
    猜你喜欢
    • 2017-04-15
    • 2018-09-21
    • 2021-12-28
    • 1970-01-01
    • 1970-01-01
    • 2019-01-26
    • 1970-01-01
    • 2014-11-10
    相关资源
    最近更新 更多