python - 从彭博社抓取数据

标签 python web-scraping beautifulsoup

我想从 Bloomberg 网站上抓取数据。 “IBVC:IND”下的数据 Caracas Stock Exchange Stock Market Index”需要被抓取。

到目前为止,这是我的代码:

import requests
from bs4 import BeautifulSoup as bs

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '
                  'Chrome/58.0.3029.110 Safari/537.36 '
}
res = requests.get("https://www.bloomberg.com/quote/IBVC:IND", headers=headers)

soup = bs(res.content, 'html.parser')
# print(soup)
itmes = soup.find("div", {"class": "snapshot__0569338b snapshot"})

open_ = itmes.find("span", {"class": "priceText__1853e8a5"}).text
print(open_)
prev_close = itmes.find("span", {"class": "priceText__1853e8a5"}).text

我无法在 HTML 中找到所需的值。我应该使用哪个库来处理这个问题?我目前正在使用 BeautifulSoup 和 Requests。

最佳答案

如其他答案所示,内容是通过 JavaScript 生成的,因此不在纯 html 中。对于给定的问题,提出了两种不同的攻角

  • Selenium 又名 The Big Guns:这将使您能够在浏览器中自动执行几乎任何任务。尽管在速度方面要付出一定的代价。
  • API 请求 又名Thought Through:这并不总是可行的。然而,如果是这种情况,则效率会

我详细说明第二个。 @ViniciusDAvila 已经为此类解决方案制定了典型的蓝图:导航到该站点,检查网络 并确定哪个请求负责获取数据。

一旦完成,剩下的就是执行问题了:

抓取工具

import requests
import json
from urllib.parse import quote


# Constants
HEADERS = {
    'Host': 'www.bloomberg.com',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:70.0) Gecko/20100101 Firefox/70.0',
    'Accept': '*/*',
    'Accept-Language': 'de,en-US;q=0.7,en;q=0.3',
    'Accept-Encoding': 'gzip, deflate, br',
    'Referer': 'https://www.bloomberg.com/quote/',
    'DNT': '1',
    'Connection': 'keep-alive',
    'TE': 'Trailers'
}
URL_ROOT = 'https://www.bloomberg.com/markets2/api/datastrip'
URL_PARAMS = 'locale=en&customTickerList=true'
VALID_TYPE = {'currency', 'index'}


# Scraper
def scraper(object_id: str = None, object_type: str = None, timeout: int = 5) -> list:
    """
    Get the Bloomberg data for the given object.
    :param object_id: The Bloomberg identifier of the object.
    :param object_type: The type of the object. (Currency or Index)
    :param timeout: Maximal number of seconds to wait for a response.
    :return: The data formatted as dictionary.
    """
    object_type = object_type.lower()
    if object_type not in VALID_TYPE:
        return list()
    # Build headers and url
    object_append = '%s:%s' % (object_id, 'IND' if object_type == 'index' else 'CUR')
    headers = HEADERS
    headers['Referer'] += object_append
    url = '%s/%s?%s' % (URL_ROOT, quote(object_append), URL_PARAMS)
    # Make the request and check response status code
    response = requests.get(url=url, headers=headers)
    if response.status_code in range(200, 230):
        return response.json()
    return list()

测试

# Index
object_id, object_type = 'IBVC', 'index'
data = scraper(object_id=object_id, object_type=object_type)
print('The open price for %s %s is: %d' % (object_type, object_id, data[0]['openPrice']))
# The open price for index IBVC is: 50094

# Exchange rate
object_id, object_type = 'EUR', 'currency'
data = scraper(object_id=object_id, object_type=object_type)
print('The open exchange rate for USD per {} is: {}'.format(object_id, data[0]['openPrice']))
# The open exchange rate for USD per EUR is: 1.0993

关于python - 从彭博社抓取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58064494/

相关文章:

python - 如何调用产生的函数(python 2.7)

python - 使用 Python 抓取数据点

python - 读取从 selenium 检索到的 soup 中的 html 源代码

python - 基本的 BeautifulSoup 维基百科抓取

python - 使用 BeautifulSoup 提取链接的标题

python - 如何在运行时轻松地在 PyQt 或 PySide 之间进行选择?

python - `python -X importtime` 增加了多少开销?

python - 使用 Pyquery、Requests 和 Gadget 选择器提取 Web 元素

javascript - 使用正则表达式/列表获取正确的数据

python |使用 ctypes 访问 dll