xpath爬取猪八戒网案例

import requests
from lxml import etree

url = "https://jingzhou.zbj.com/rjkf/f.html?fr=zbj.sy.zyyw_2nd.lv2"
response = requests.get(url)
# print(response.text)
response.close()

html = etree.HTML(response.text)
divs = html.xpath("/html/body/div[6]/div/div/div[3]/div[5]/div[1]/div")
for div in divs:
    price = div.xpath("./div/div/div[2]/div[2]/div[1]/span[1]/text()")[0].strip("¥")
    title = div.xpath("./div/div/div[2]/div[2]/div[2]/p/a/text()")
    com_name = div.xpath("./div/div/div[1]/div[1]/p/a/text()")
    location = div.xpath("./div/div/div[1]/div[1]/div/span/text()")
    print(title)

代码中的节点路径根据实际情况来写,可以在浏览器中查看网页的源代码对照完成

上一篇:div和span在网页中的应用


下一篇:学习笔记