【问题标题】:force xpath to return a string lxml强制 xpath 返回一个字符串 lxml
【发布时间】:2015-12-25 09:56:00
【问题描述】:

我正在使用lxml,并且我有一个来自 Google Scholar 的废弃页面。以下是一个最小的工作示例和我尝试过的事情。

In [56]: seed = "https://scholar.google.com/citations?view_op=search_authors&hl=en&mauthors=label:machine_learning"

In [60]: page = urllib2.urlopen(seed).read()

In [63]: tree = html.fromstring(page)

In [64]: xpath = '(/html/body/div[1]/div[4]/div[2]/div/span/button[2]/@onclick)[1]'

In [65]: tree.xpath(xpath)
#first element returns as list
Out[65]: ["window.location='/citations?view_op\\x3dsearch_authors\\x26hl\\x3den\\x26oe\\x3dASCII\\x26mauthors\\x3dlabel:machine_learning\\x26after_author\\x3dVCoCALPY_v8J\\x26astart\\x3d10'"]         

In [66]: xpath = '(/html/body/div[1]/div[4]/div[2]/div/span/button[2]/@onclick)[2]'

#there is no second element
In [67]: tree.xpath(xpath)
Out[67]: []     

In [70]: xpath = '(/html/body/div[1]/div[4]/div[2]/div/span/button[2]/@onclick)'

#The list contains only one element
In [71]: tree.xpath(xpath)
Out[71]: ["window.location='/citations?view_op\\x3dsearch_authors\\x26hl\\x3den\\x26oe\\x3dASCII\\x26mauthors\\x3dlabel:machine_learning\\x26after_author\\x3dVCoCALPY_v8J\\x26astart\\x3d10'"]         

根据文档here,返回值可以是智能字符串,但我无法从 xpath 函数获取字符串输出。如何编写 xpath 以便从 xpath 获得字符串输出

【问题讨论】:

    标签: python xpath lxml


    【解决方案1】:

    您可以使用 XPath 表达式 string(/html/body/div[1]/div[4]/div[2]/div/span/button[2]/@onclick),在这种情况下您会得到一个简单的字符串值。

    【讨论】:

    • 是的。我确实得到了一个字符串。谢谢。您能否详细说明我采用的方法存在的问题。
    • 据我了解,当 XPath 表达式选择一个节点集时,在 Python 中你会得到一个列表,如果所选节点集为空,则为空列表,或者列表选择的节点,如果元素节点被选择,或者在文本节点或属性节点选择的情况下,带有智能字符串的列表。如果您知道您的 XPath 至少选择了一个属性并且您想要它的值而不是具有单个值的列表,那么您总是可以使用tree.xpath(xpath)[0]
    • 是的,我可以,但我将其写为循环的一部分,并非所有类型的 xpath 都返回单个元素。因此写tree.xpath(xpath)[0] 不是一种选择,但上面的解决方案工作得很好。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-29
    • 1970-01-01
    • 2017-03-21
    • 2011-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多