gpt4 book ai didi

python - 从位于网站的图表中解析表格项时遇到问题

转载 作者:行者123 更新时间:2023-12-04 11:33:13 24 4
gpt4 key购买 nike

我正在尝试提取网页中图表上可用的表格内容。只有当有人将光标悬停在该区域内时,这些表格的内容才可见。一张这样的表是 this one .

Webpage address

表格所在的图表标题为 EPS consensus revisions : last 18 months .

到目前为止,我已经尝试过:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

link = "https://www.marketscreener.com/SUNCORP-GROUP-LTD-6491453/revisions/"

driver = webdriver.Chrome()
driver.get(link)
wait = WebDriverWait(driver, 10)
for items in wait.until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, "#graphRevisionBNAeec span > table tr"))):
data = [item.text for item in items.find_elements_by_css_selector("td")]
print(data)
driver.quit()

当我运行上面的脚本时,它会抛出错误 raise TimeoutException(message, screen, stacktrace):selenium.common.exceptions.TimeoutException: Message:指着这个 for items in wait.until()线。

来自多个表中的单个表的输出应如下所示:
Period: Thursday, Aug 22, 2019
Number of upgrading estimates: 0
Number of unchanged estimates: 7
Number of Downgrading estimates: 0
High Value: 0.90 AUD
Mean Value: 0.85 AUD
Low Value: 0.77 AUD

如何从该图中获取这些表格的内容?

EDIT: I'm still expecting any solution based purely on any browser simulator.

最佳答案

由于三个重要原因,直接查询网站的后端比使用 selenium 抓取前端要好得多:

  • 速度 :直接使用 API 更快、更高效,因为它只获取您需要的数据,而不必等待 javascript 运行或像素渲染,并且没有运行 webdriver 的开销。
  • 稳定性 :通常对前端的更改比对后端的更改更频繁且难以跟踪。如果您的代码依赖于站点的前端,那么当他们进行一些 UI 更改时,它可能会很快停止工作。
  • 精度 : 有时 UI 中显示的数据不准确或不完整。例如,在本网站中,所有数字都四舍五入到小数点后两位,而后端有时会提供两倍多的准确数据。

  • 以下是您可以轻松使用后端 API 的方法:

    import requests
    # API url found using chrome devtools
    url = 'https://www.marketscreener.com/charting/afDataFeed.php?codeZB=6491453&t=eec&sub_t=bna&iLang=2'
    # We are mocking a chrome browser because the API is blocking python requests apparently
    headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36'}
    # Make a request to the API and parse the JSON response
    data = requests.get(url, headers=headers).json()[0]
    # A function to find data for a specific date
    def get_vals(date):
    vals = []
    for items in data:
    for item in items:
    if item['t'] == date:
    vals.append(item['y'])
    break
    return vals
    # Use the function above with the example table given in the question
    print(get_vals('Thursday, Aug 22, 2019'))

    运行此输出列表 [0.9, 0.84678, 0.76628, 0, 7, 0] ,如您所见,这是您希望从您作为示例提供的表中提取的数据。

    关于python - 从位于网站的图表中解析表格项时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57654639/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com