首页 文章

Xpath在开发控制台中公开文本节点,但在python shell中没有

提问于
浏览
1

我正在编写一个web scraper,它应该是从html表here中的行中抓取数据 . 我可以通过在firebug中使用这个xpath来公开表中行内的所有文本: $x('.//*[@class="statistics"]/tbody/tr/th/a/text()') . 运行它会显示表中所有文本节点的完整集 .

我将此xpath基于我之前用于此站点的另一个类似的xpath,它也返回所有所需的文本节点: './/*[@class="productionsEvent"]/text()' . 出于某种原因,当我尝试在简单地请求html之后从python shell内部的statistics表的行中打印文本时,我得到一个空列表 . 什么可能xpath不在shell中工作?

1 回答

  • 1

    这是因为 tbody - 它是由浏览器插入的,当你通过 urllib2requests 下载页面时你不会得到它:

    >>> import requests
    >>> from lxml.html import fromstring
    >>> 
    >>> url = "https://www.federalreserve.gov/releases/h10/hist/"
    >>> response = requests.get(url)
    >>> root = fromstring(response.content)
    >>> root.xpath('.//*[@class="statistics"]/tbody/tr/th/a/text()')  # with tbody
    []
    >>> root.xpath('.//*[@class="statistics"]//tr/th/a/text()')  # without tbody
    ['Australia', 'Brazil', 'Canada', 'China, P.R.', 'Denmark', 'EMU member countries', 'Greece', 'Hong Kong', 'India', 'Japan', 'Malaysia', 'Mexico', 'New Zealand', 'Norway', 'Singapore', 'South Africa', 'South Korea', '\r\n        ', 'Sri Lanka', 'Sweden', 'Switzerland', 'Taiwan', 'Thailand', 'United Kingdom', 'Venezuela']
    

相关问题