Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/337.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python3.4:LXML web抓取_Python_Lxml - Fatal编程技术网

Python3.4:LXML web抓取

Python3.4:LXML web抓取,python,lxml,Python,Lxml,我正在使用以下代码尝试返回该网站上的股票列表。代码的结果是一个空列表。我从google chromium开发工具复制xpath。我做错了什么 from lxml import html import requests url = 'http://en.wikipedia.org/wiki/List_of_S%26P_500_companies' resp = requests.get(url) tree = html.fromstring(resp.text) tickers = tre

我正在使用以下代码尝试返回该网站上的股票列表。代码的结果是一个空列表。我从google chromium开发工具复制xpath。我做错了什么

from lxml import html
import requests


url = 'http://en.wikipedia.org/wiki/List_of_S%26P_500_companies'

resp = requests.get(url)
tree = html.fromstring(resp.text)

tickers = tree.xpath(r'//*[@id="mw-content-text"]/table[1]/tbody/tr[1]/td[1]/a')

print(tickers)

浏览器添加缺少的HTML元素,HTML规范声明这些元素是模型的一部分
lxml
不会将这些添加到中

最常见的此类元素是
元素。您的文档没有这样的元素,但Chrome有,他们将其放在XPath中。
元素中的另一个这样的元素;同样,原始HTML缺少它,但是Chrome将它放进了
行,其中包含
元素

因此,正确的XPath表达式是:

tickers = tree.xpath(r'//*[@id="mw-content-text"]/table[1]/tr[2]/td[1]/a')
e、 g.表格中的第二行,该行中的第一个表格单元格

请注意,
lxml
可以直接加载URL;在这种特定情况下,您实际上不需要使用
请求

>>> from lxml import html
>>> url = 'http://en.wikipedia.org/wiki/List_of_S%26P_500_companies'
>>> tree = html.parse(url)
>>> tree.xpath(r'//*[@id="mw-content-text"]/table[1]/tr[2]/td[1]/a')
[<Element a at 0x10445e628>]
>>> tree.xpath(r'//*[@id="mw-content-text"]/table[1]/tr[2]/td[1]/a')[0].text
'MMM'
>>> tree.xpath(r'//*[@id="mw-content-text"]/table[1]/tr[2]/td[1]/a')[0].attrib['href']
'https://www.nyse.com/quote/XNYS:MMM'

现在,如果我想要完整的股票行情表呢?sp500的每个组成部分都有多个tr和相应的td标签。@aranfleel:只需删除
[1]
选择器上的
tr
限制。如果我想用lxml打印整个表格怎么办。。。我最多可以看到第三个td标签,但之后它会返回nothing@AranFreel:仅考虑第1、2、3和6列具有链接标记。这才有意义:-)
links = tree.xpath(r'//*[@id="mw-content-text"]/table[1]/tr/td[1]/a')
for link in links:
    print(link.text, link.attrib['href'])