gpt4 book ai didi

来自 yahoo 的 python lxml etree applet 信息

转载 作者:太空狗 更新时间:2023-10-29 21:02:55 25 4
gpt4 key购买 nike

Yahoo Finance 更新了他们的网站。我有一个用于提取分析师建议的 lxml/etree 脚本。然而,现在分析师的建议已经存在,但只是以图形的形式出现。您可以在 this page 上查看示例.右侧栏中称为推荐趋势的图表显示了显示强买入、买入、持有、表现不佳和卖出的分析师报告的数量。

我的猜测是雅虎会在接下来的一段时间内对页面进行一些调整,但这让我想知道是否可以通过任何合理的方式提取这些数据?

  1. 我的意思是,有没有办法让图形与它一起工作?
  2. 即使成功了,是否有合理的方法从图形中提取数据?

我以前是这样获取源码的:

url = 'https://finance.yahoo.com/quote/'+code+'/analyst?p='+code
tree = etree.HTML(urllib.request.urlopen(url).read())

然后在html树中查找数据。但显然现在这是不可能的。

最佳答案

该页面非常动态,涉及在浏览器中执行的大量 javascript。遵循@Padraic 关于切换到 selenium 的建议,这是一个完整的示例工作代码,它在最后生成一个月度趋势字典。每个条形的值按条形高度的比例计算:

from pprint import pprint

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

driver = webdriver.Chrome()
driver.maximize_window()
driver.get("https://finance.yahoo.com/quote/CSX/analysts?p=CSX")

# wait for the chart to be visible
wait = WebDriverWait(driver, 10)
trends = wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, "section[data-reactid$=trends]")))
chart = trends.find_element_by_css_selector("svg.ratings-chart")

# get labels
month_names = [month.text for month in chart.find_elements_by_css_selector("g.x-axis g.tick")]
trend_names = [trend.text for trend in trends.find_elements_by_css_selector("table tr > td:nth-of-type(2)")]

# construct month-to-trend dictionary
data = {}
months = chart.find_elements_by_css_selector("g[transform]:not([class])")
for month_name, month_data in zip(month_names, months):
total = month_data.find_element_by_css_selector("text.total").text
data[month_name] = {'total': total}

bars = month_data.find_elements_by_css_selector("g.bar rect")

# let's calculate the values of bars as proportions of a bar height
heights = {trend_name: int(bar.get_attribute("height")) for trend_name, bar in zip(trend_names[::-1], bars)}
total_height = sum(heights.values())
for trend_name, bar in zip(trend_names, bars):
data[month_name][trend_name] = heights[trend_name] * 100 / total_height

driver.close()

pprint(data)

打印:

{u'Aug': {u'Buy': 19,
u'Hold': 45,
u'Sell': 3,
u'Strong Buy': 22,
u'Underperform': 8,
'total': u'26'},
u'Jul': {u'Buy': 18,
u'Hold': 44,
u'Sell': 3,
u'Strong Buy': 25,
u'Underperform': 7,
'total': u'27'},
u'Jun': {u'Buy': 21,
u'Hold': 38,
u'Sell': 3,
u'Strong Buy': 28,
u'Underperform': 7,
'total': u'28'},
u'May': {u'Buy': 21,
u'Hold': 38,
u'Sell': 3,
u'Strong Buy': 28,
u'Underperform': 7,
'total': u'28'}}

total 值是您在每个条形图顶部看到的标签。

希望这至少对您来说是一个好的开始。如果您希望我详细说明代码的任何部分或需要任何其他信息,请告诉我。

关于来自 yahoo 的 python lxml etree applet 信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39007227/

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