python - 使用 BeautifulSoup 从 investing.com 抓取 BTC/ETH 数据

标签 python beautifulsoup

我已经编写了一些代码来从 investing.com 上抓取 BTC/ETH 时间序列,它运行良好。但是,我需要更改请求调用,以便下载的数据来自 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 和最后一整天,即总是昨天)

最佳答案

小背景

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

我怎么知道的?

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

Under Networks tab view

现在该怎么办?

你需要聪明一点,对你的 python 代码进行 3 更改。

  • 将请求从 GET 更改为 POST

  • 发送表单数据作为该请求的负载。

  • 将 url 更改为您刚刚在 Headers 标签中看到的那个。

    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)

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

关于python - 使用 BeautifulSoup 从 investing.com 抓取 BTC/ETH 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53890493/

相关文章:

python - 如何使用python连接到linux端口

css - Web 服务器在进行数据抓取时响应缓慢

python - 仅从 python 中的 td 选择价格值

python - 带 Selenium 的 Instagram 登录脚本,无法执行 .send_keys ('test' )

python - 聚类内部聚类是数据表的嵌套聚类,是多类聚类

python - 获取 url 时出现 UnicodeEncodeError

python - 使用 Python 将 HTML 渲染为纯文本

python - python中的beautifulsoup解析错误——垃圾字符

python - 方法与属性哪个更快?

python - 使用户制作的 HTML 模板安全