簡體   English   中英

強制xpath返回字符串lxml

[英]force xpath to return a string lxml

我正在使用lxml並且從Google學術搜索中lxml了一個頁面。 以下是一個最小的工作示例以及我嘗試過的事情。

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'"]         

根據此處的文檔,返回值可以是智能字符串,但是我無法從xpath函數獲得字符串輸出。 如何編寫xpath,以便從xpath獲取字符串輸出

您可以使用XPath表達式string(/html/body/div[1]/div[4]/div[2]/div/span/button[2]/@onclick) ,在這種情況下,您將獲得一個簡單的字符串值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM