【问题标题】:How do you webscrape data from a "span" tag with a "data-reactid" using beautifulsoup in python?你如何在python中使用beautifulsoup从带有“data-reactid”的“span”标签中抓取数据?
【发布时间】:2019-08-29 04:50:06
【问题描述】:

我正在尝试从雅虎财经中提取股票的实时价格数据。此信息包含在带有“class”和“data-reactid”的“span”标签中。我无法从这个 span 标签中提取信息。

当我输入我的代码时,我没有得到任何输出,也没有得到任何错误。

我已经尝试了这个问题的几乎所有其他答案,但没有一个对我有用。

<--HTML Code-->
<span class="Trsdu(0.3s) Fw(b) Fz(36px) Mb(-4px) D(ib)" data-reactid="34">197.00</span>
#Python Script
my_url = "https://finance.yahoo.com/quote/AAPL?p=AAPL&.tsrc=fin-srch"
u_client = u_req(my_url)

page_html = u_client.read()
u_client.close()

page_soup = soup(page_html, "html.parser")
container = page_soup.find('span', {"data-reactid":'34'})

我想得到“197.00”(股票的实时价格)的输出作为输出。

【问题讨论】:

  • 什么是u_req?
  • @gmds 我认为来自from urllib.request import urlopen as u_req
  • @Kush G。我认为这是因为输出是用 JavaScript 呈现的。所以你需要selenium 而不是BeautifulSoup

标签: python html python-3.x web-scraping beautifulsoup


【解决方案1】:

您可以通过多种方式获取它。这是其中之一:

import requests
from bs4 import BeautifulSoup

res = requests.get('https://finance.yahoo.com/quote/AAPL')
soup = BeautifulSoup(res.text, 'lxml')
price = soup.select_one('#quote-market-notice').find_all_previous()[2].text
print(price)

另一种方式:

price = soup.select_one("[class*='smartphone_Mt'] span").text
print(price)

【讨论】:

    【解决方案2】:

    读取 url 时 data-reactid 不知何故更改为 14。

    page_soup = soup(page_html, "html.parser")
    container = page_soup.find('span', {"data-reactid":'14'})
    if container:
        print(container.text)
    

    【讨论】:

      【解决方案3】:

      鉴于 data-reactid 可以更改,我将使用唯一的类来选择。按班级选择也更快。

      import requests
      from bs4 import BeautifulSoup as bs
      r = requests.get('https://finance.yahoo.com/quote/AAPL/')
      soup = bs(r.content, 'lxml')
      print(soup.select_one('.Mb\(-4px\)').text)
      

      【讨论】:

        【解决方案4】:

        我在 chrome 中打开 URL 并按 F12。单击网络选项卡从页面显示此查询:https://query1.finance.yahoo.com/v8/finance/chart/AAPL?region=US&lang=en-US&includePrePost=false&interval=2m&range=1d&corsDomain=finance.yahoo.com&.tsrc=finance

        我建议探索底层 AJAX 调用,这些调用似乎呈现格式良好的 JSON 结果,并查看 URL 中可以修改的一些参数。

        【讨论】:

          猜你喜欢
          • 2020-05-19
          • 1970-01-01
          • 2021-06-05
          • 1970-01-01
          • 1970-01-01
          • 2019-04-21
          • 1970-01-01
          • 1970-01-01
          • 2016-11-04
          相关资源
          最近更新 更多