python爬虫之xpath解析

这里我们用xpath爬取猪八戒网的信息

https://chongqing.zbj.com/search/f/?kw=python

首先我们打开猪八戒网,随便搜索一个服务,得到下面界面
在这里插入图片描述
然后我们对网页进行分析,我们先打开网页源代码,观察我们所要爬取的内容是否存在于网页源代码内
在这里插入图片描述
可以看出我们需要的内容就存在于网页源代码内,这时候我们需要分析网页的层级结构。
这是我们需要提取内容的所有供应商:
在这里插入图片描述
通过以下方法就可以获得所有供应商的层级关系,后面获取具体内容的层级关系也是依次类推
在这里插入图片描述
好了,我们上代码:

# @Time:2021/11/2412:42
# @Author:中意灬
# @File:八戒网.py
# @ps:tutu qqnum:2117472285

#拿到网页源代码
#解析并获取数据
#保存数据
import csv
import requests
from  lxml import etree
url="https://chongqing.zbj.com/search/f/?kw=python"
resp=requests.get(url)
html=resp.text
tree=etree.HTML(html)#将网页源代码生成一个etree的对象
divs=tree.xpath("/html/body/div[6]/div/div/div[2]/div[5]/div[1]/div")#拿到所有的供应商
with open("猪八戒网.csv",'w',encoding='utf-8',newline='') as f:#创建一个文件,转码为utf-8
    writer=csv.writer(f)
    writer.writerow(["名称","价格","供应商","交易记录","地点"])
    for div in divs:#每一天个供应商
    #./表示当前节点,运用了相对查询
        price=div.xpath("./div/div/a[2]/div[2]/div[1]/span[1]/text()")[0].strip("¥")#提取价格
        transactionrecord=div.xpath("./div/div/a[2]/div[2]/div[1]/span[2]/text()")[0]#提取交易记录
        title="python".join(div.xpath("./div/div/a[2]/div[2]/div[2]/p/text()"))#提取名称
        contractor="".join(div.xpath("./div/div/a[1]/div[1]/p/text()")).strip("\n")#提取供应商
        place=div.xpath("./div/div/a[1]/div[1]/div/span/text()")[0]#提取地点
        writer.writerow([title,price,contractor,transactionrecord,place])#存入数据
print("over!")

运行结果:
在这里插入图片描述
在这里插入图片描述

Guess you like

Origin blog.csdn.net/qq_55977554/article/details/121518741