【问题标题】:Scraping data from investing.com for BTC/ETH using BeautifulSoup使用 BeautifulSoup 从investing.com 获取BTC/ETH 数据
【发布时间】:2018-12-21 20:31:30
【问题描述】:

我已经编写了一些代码来从investing.com 上抓取BTC/ETH 时间序列,它运行良好。但是,我需要更改 requests 调用,以便下载的数据来自 Kraken 而不是 bitfinex 默认值,以及来自 01/06/2016 而不是默认开始时间。可以在网页上手动设置此选项,但我不知道如何通过请求调用发送该选项,除非它可能涉及使用“数据”参数。感谢任何建议。

谢谢,

公里

已经用 python 编写的代码,默认情况下可以正常工作

import requests
from bs4 import BeautifulSoup
import os
import numpy as np

# BTC scrape https://www.investing.com/crypto/bitcoin/btc-usd-historical-data
# ETH scrape https://www.investing.com/crypto/ethereum/eth-usd-historical-data

ticker_list = [x.strip() for x in open("F:\\System\\PVWAVE\\Crypto\\tickers.txt", "r").readlines()]
urlheader = {
  "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.75 Safari/537.36",
  "X-Requested-With": "XMLHttpRequest"
}

print("Number of tickers: ", len(ticker_list))

for ticker in ticker_list:
    print(ticker)
    url = "https://www.investing.com/crypto/"+ticker+"-historical-data"
    req = requests.get(url, headers=urlheader, data=payload)
    soup = BeautifulSoup(req.content, "lxml")

    table = soup.find('table', id="curr_table")
    split_rows = table.find_all("tr")

    newticker=ticker.replace('/','\\')

    output_filename = "F:\\System\\PVWAVE\\Crypto\\{0}.csv".format(newticker)
    os.makedirs(os.path.dirname(output_filename), exist_ok=True)
    output_file = open(output_filename, 'w')
    header_list = split_rows[0:1]
    split_rows_rev = split_rows[:0:-1]

    for row in header_list:
        columns = list(row.stripped_strings)
        columns = [column.replace(',','') for column in columns]
        if len(columns) == 7:
            output_file.write("{0}, {1}, {2}, {3}, {4}, {5}, {6} \n".format(columns[0], columns[2], columns[3], columns[4], columns[1], columns[5], columns[6]))

    for row in split_rows_rev:
        columns = list(row.stripped_strings)
        columns = [column.replace(',','') for column in columns]
        if len(columns) == 7:
            output_file.write("{0}, {1}, {2}, {3}, {4}, {5}, {6} \n".format(columns[0], columns[2], columns[3], columns[4], columns[1], columns[5], columns[6]))

    output_file.close()

为默认交换和默认日期范围下载数据,但我想指定 Kraken 和默认开始和结束时间(01/06/16 和最后一整天,即总是昨天)

【问题讨论】:

    标签: python beautifulsoup


    【解决方案1】:

    小背景

    有很多网站使用称为forms的东西根据用户活动(例如您填写用户名和密码的登录页面)将数据发送到服务器,或者当你点击一个按钮。类似的事情正在这里发生。

    我怎么知道的?

    • 更改默认页面并转到Kraken 历史数据 页面。您将看到 url 已更改为 https://www.investing.com/crypto/bitcoin/btc-usd-historical-data?cid=49799
    • 现在,右键单击页面并单击检查。 查看刚刚打开的分屏的顶行。点击网络标签。此选项卡将显示您在浏览器中访问的任何网页的请求/响应周期。
    • 搜索您看到的红色按钮旁边的清除按钮并单击它。现在,你有了一张白纸。当您更改该页面上的日期时,您将能够看到正在发送到服务器的请求。
    • 根据需要更改日期,然后单击应用。您将看到名为 HistoricalDataAjax 的请求已发送到服务器(请参阅下面的附图以获得更清晰的信息)。单击它并在 标题 选项卡中向下滚动。您可以看到一个名为表单数据的部分。这是发送到服务器的额外隐藏(但不是那么隐藏)信息。它作为 POST 请求发送,因为您在 url 中看不到任何变化。
    • 您还可以在同一 Headers 部分看到 Request URLhttps://www.investing.com/instruments/HistoricalDataAjax

    现在该怎么办?

    您需要聪明,并在您的 Python 代码中进行 3 项更改。

    • 将请求从 GET 更改为 POST
    • 发送表单数据作为该请求的负载。
    • 将网址更改为您刚刚在 标题 选项卡中看到的网址。

      url = "https://www.investing.com/instruments/HistoricalDataAjax"

      payload = {'header': 'BTC/USD Kraken 历史数据', 'st_date': '12/01/2018', 'end_date': '12/01/2018', 'sort_col': 'date' , 'action': 'historical_data', 'smlID': '145284', 'sort_ord': 'DESC', 'interval_sec': 'Daily', 'curr_id': '49799'}

      requests.post(url, data=payload, headers=urlheader)

    进行上述更改并让代码的其他部分保持不变。你会得到你想要的结果。您也可以根据需要修改日期。

    【讨论】:

    • 不仅是表单数据,而且我今天注意到一些标题是必要的,否则它会将您重定向到主页。我让它和Content-Type: application/x-www-form-urlencoded,Accept: */*,Accept-Encoding: gzip, deflate, br,Connection: keep-alive,User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.74 Safari/537.36 Edg/99.0.1150.46,Origin: https://www.investing.com,x-requested-with: XMLHttpRequest,一起工作了
    猜你喜欢
    • 2021-09-23
    • 2021-10-22
    • 2020-09-14
    • 2021-10-31
    • 2021-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多