【发布时间】:2015-06-10 08:07:48
【问题描述】:
我正在尝试获取股票的公司名称、部门和行业。我下载了'https://finance.yahoo.com/q/in?s={}+Industry'.format(sign) 的HTML,然后尝试用lxml.html 中的.xpath() 解析它。
要获取我要抓取的数据的 XPath,我在 Chrome 中转到该站点,右键单击该项目,单击 Inspect Element,右键单击突出显示的区域,然后单击 Copy XPath .这在过去一直对我有用。
这个问题可以用下面的代码复现(我以苹果为例):
import requests
from lxml import html
page_p = 'https://finance.yahoo.com/q/in?s=AAPL+Industry'
name_p = '//*[@id="yfi_rt_quote_summary"]/div[1]/div/h2/text()'
sect_p = '//*[@id="yfncsumtab"]/tbody/tr[2]/td[1]/table[2]/tbody/tr/td/table/tbody/tr[1]/td/a/text()'
indu_p = '//*[@id="yfncsumtab"]/tbody/tr[2]/td[1]/table[2]/tbody/tr/td/table/tbody/tr[2]/td/a/text()'
page = requests.get(page_p)
tree = html.fromstring(page.text)
name = tree.xpath(name_p)
sect = tree.xpath(sect_p)
indu = tree.xpath(indu_p)
print('Name: {}\nSector: {}\nIndustry: {}'.format(name, sect, indu))
给出这个输出:
Name: ['Apple Inc. (AAPL)']
Sector: []
Industry: []
它没有遇到任何下载困难,因为它能够检索name,但其他两个不起作用。如果我分别用tr[1]/td/a/text() 和tr[1]/td/a/text() 替换它们的路径,它会返回:
Name: ['Apple Inc. (AAPL)']
Sector: ['Consumer Goods', 'Industry Summary', 'Company List', 'Appliances', 'Recreational Goods, Other']
Industry: ['Electronic Equipment', 'Apple Inc.', 'AAPL', 'News', 'Industry Calendar', 'Home Furnishings & Fixtures', 'Sporting Goods']
显然我可以切出每个列表中的第一项来获取我需要的数据。
我不明白的是,当我将 tbody/ 添加到开头 (//tbody/tr[#]/td/a/text()) 时,它再次失败,即使 Chrome 中的控制台清楚地将 trs 显示为 tbody 的孩子元素。
为什么会这样?
【问题讨论】: