获取搜索元素的Xpath

时间:2017-03-06 13:12:31

标签: python xpath

我可以使用此代码从网页获取产品列表

from lxml import html
import requests

page = requests.get('http://monument.pl/pol_m_DESKOROLKA_Deski-162.html')
tree = html.fromstring(page.content)
VENDORLISTn = tree.xpath('//a[@class="firm_name"]/text()')
print VENDORLISTn

我得到以下结果

['Almost', 'Almost', 'Almost', 'Enjoi', 'Real', 'Boulevard', 'Almost', 'Almost', 'Enjoi', 'Enjoi', 'Enjoi', 'Blind', 'Blind', 'Blind', 'Blind', 'Blind', 'Blind', 'Blind', 'Cliche', 'Blind', 'Blind', 'Blind', 'Enjoi', 'Enjoi', 'Enjoi', 'Enjoi', 'Enjoi', 'Enjoi', 'Enjoi', 'Antihero']

如何获取这些元素的路径列表?它可能看起来像这样:

['//*[@id="search"]/table/tbody/tr[1]/td[1]/div/div[3]/div/a','//*[@id="search"]/table/tbody/tr[1]/td[2]/div/div[3]/div/a',etc....

1 个答案:

答案 0 :(得分:0)

VENDORLISTn只是字符串list。我想没有办法为此生成XPath,但您可以为每个链接获得绝对XPath,如下所示:

from lxml import etree
from lxml import html
import requests

page = requests.get('http://monument.pl/pol_m_DESKOROLKA_Deski-162.html')
tree = html.fromstring(page.content)
VENDORLISTn = tree.xpath('//a[@class="firm_name"]')
for link in VENDORLISTn:
    etree.ElementTree(tree).getpath(link)

输出:

'/html/body/div[1]/div/div[2]/div/div[2]/div/div[7]/table/tr[1]/td[1]/div/div[3]
/div/a'
'/html/body/div[1]/div/div[2]/div/div[2]/div/div[7]/table/tr[1]/td[2]/div/div[3]
/div/a'
'/html/body/div[1]/div/div[2]/div/div[2]/div/div[7]/table/tr[1]/td[3]/div/div[3]
/div/a'
....