【问题标题】:How to extract a single element from webpage?如何从网页中提取单个元素?
【发布时间】:2017-07-21 15:20:51
【问题描述】:

我希望从以下网页中提取单个值作为文本。

Cascade River Rustic Campground

具体来说,我在“站点数量”文本后面的“4”值之后(见截图)

我已经能够使用Chrome隔离xpath,如下:

//*[@id="act_1"]/div[1]/table/tbody/tr/td[2]

以下代码生成一个空列表:

import urllib2
from lxml import etree

url = "https://www.fs.usda.gov/recarea/superior/recreation/camping-cabins/recarea/?recid=36913&actid=29"

response = urllib2.urlopen(url)
htmlparser = etree.HTMLParser()
tree = etree.parse(response, htmlparser)
x = tree.xpath('//*[@id="act_1"]/div[1]/table/tbody/tr/td[2]')
print x 

预期的输出应该是:

>>> print x
['4']

如何提取网页中的单个元素(即“4”)?

【问题讨论】:

    标签: python macos xpath web-scraping lxml


    【解决方案1】:

    似乎这个 xpath 对我有用(注意没有 tbody)并使用 text() 从节点中提取文本:

    x = tree.xpath('//*[@id="act_1"]/div[1]/table/tr/td[2]/text()')
    
    print(x[0].strip())
    # 4
    

    【讨论】:

      猜你喜欢
      • 2014-07-28
      • 1970-01-01
      • 2011-03-01
      • 2015-09-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多