这里我们用xpath爬取猪八戒网的信息
https://chongqing.zbj.com/search/f/?kw=python
首先我们打开猪八戒网,随便搜索一个服务,得到下面界面  然后我们对网页进行分析,我们先打开网页源代码,观察我们所要爬取的内容是否存在于网页源代码内  可以看出我们需要的内容就存在于网页源代码内,这时候我们需要分析网页的层级结构。 这是我们需要提取内容的所有供应商:  通过以下方法就可以获得所有供应商的层级关系,后面获取具体内容的层级关系也是依次类推  好了,我们上代码:
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)
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:
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!")
运行结果:  
|