【问题标题】:Scrape data in python from yahoo finance从 yahoo Finance 在 python 中抓取数据
【发布时间】:2019-11-18 16:53:31
【问题描述】:

我想从 yahoo Finance 中抓取特定符号的数据。

我可以抓取表格格式,但不能抓取非表格格式。我应用相同的原理在同一页面中抓取信息,但没有结果。

到目前为止,我可以从https://finance.yahoo.com/quote/AAPL/profile?p=AAPL 刮下来

我用来刮表的代码是:

import numpy as np
import pandas as pd

import requests
import lxml
from lxml import html

symbol = 'AAPL'

url = 'https://finance.yahoo.com/quote/' + symbol + '/profile?p=' + symbol

page = requests.get(url)
tree = html.fromstring(page.content)

table = tree.xpath('//table') 

assert len(table) == 1 
tstring = lxml.etree.tostring(table[0], method='html')
df = pd.read_html(tstring)[0]

df

我要刮右边的桌子

Sector: Consumer Goods
Industry: Electronic Equipment
Full Time Employees: 137,000

如果您能帮助获取信息或提供一些提示和建议,我将不胜感激。

【问题讨论】:

  • 你为什么忽略你的导入?对繁殖很重要。
  • 顺便说一句,雅虎金融库已经存在
  • 如果你想抓取网页,beautifulsoup 可能比普通的 XPath 更好

标签: python yahoo-finance


【解决方案1】:

您可以使用following-sibling

import requests
from lxml import html

xp = "//span[text()='Sector']/following-sibling::span[1]"

symbol = 'AAPL'

url = 'https://finance.yahoo.com/quote/' + symbol + '/profile?p=' + symbol

page = requests.get(url)
tree = html.fromstring(page.content)

d = {}
for label in ['Sector', 'Industry', 'Full Time Employees']:
    xp = f"//span[text()='{label}']/following-sibling::span[1]"
    s = tree.xpath(xp)[0]
    d[label] = s.text_content()


print(d['Full Time Employees'])
print(d['Industry'])
print(d['Sector'])

【讨论】:

  • 如果我 print(s.text_content()) 它给出了“全职员工”的数量,那么我如何获得其他人的价值:“部门”、“行业”?有点不清楚。
  • 这个demo 输出Sector Technology 然后Industry Consumer Electronics 然后Full Time Employees 137,000 所以我不知道你错过了什么。
  • 它无法持续工作。打印只输出员工人数
  • 您似乎缺乏一些基础知识。也许您需要阅读一些教程?我已经编辑了我的答案,以展示如何访问单个值。
  • 其实我上面说过我只能报废桌子,所以我在这里和其他人问。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-04-15
  • 2021-06-07
  • 2016-05-28
  • 1970-01-01
  • 2023-01-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多