xpath获取父元素的方法
两种方法:
# 1使用../
# 2使用parent::父级元素
import requests
from lxml import etree
url = 'https://www.spzs.com/chanpin/'
resp = requests.get(url,headers={
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:99.0) Gecko/20100101 Firefox/99.0'
})
tree = etree.HTML(resp.text)
type_list = tree.xpath("//div[@class='main-pro bgfff']/div[1]/div/h2")
typell = []
for type in type_list:
typell.append((type.xpath('./text()')[0]).replace(' | ','/'))
print(len(type.xpath('./parent::div/parent::div/parent::div/div[2]/p')))
print(len(type.xpath('./../../../div[2]/p')))
print(typell)
推荐链接文章:https://blog.csdn.net/chushujin/article/details/109016922