易车网车评数据获取(2024最新版!!!)
版本与环境
- windows11
- python 3.10
用到的包
- pyquery
- requests
- random
- csv
基础准备
- Python基础
- pyquary语法
- requests请求构造
- csv文件写入
目标链接
需求
- 输入需要得到目标车评的车型构造目标链接
- 输入爬取的页数范围获取到数据
- 将获取的数据保存为csv文件
1导入需要的包
from pyquery import PyQuery
import requests
import random
import csv
2用户交互,输入需要的车型拼音(这里以奥迪A6L为例)
at_name = input("请输入车名拼音,如果不知到请先到易车网搜索https://dianping.yiche.com:")
如果不知道具体的拼音,请看下面的图片
3点击进入点评页面来根据情况决定自己要爬取的页数
比如下图,我们可以看到奥迪A6L的车评页数大致有多少以便我们决定自己爬取的页数范围
4 文件操作,创建文件并创建writer对象
fp = open(f'./{at_name}车评.csv', 'a+', encoding='utf-8', newline='')
writer = csv.writer(fp)
5 设置第三方代理(最好用自己买的)以及headers
proxies_pool = [
{'http': '114.231.46.176:8089'},
{'http': '117.69.237.179:8089'},
{'http': '183.164.243.162:8089'},
{'http': '111.224.212.41:8089'},
{'http': '117.69.236.18:8089'},
{'http': '121.41.98.141:80'},
{'http': '113.124.84.192:9999'},
{'http': '36.6.144.115:8089'},
]
proxies = random.choice(proxies_pool)
# 利用fstring来接收我们输入的车型拼音
base_url = f'https://dianping.yiche.com/{at_name}/'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36'
}
6用户交互,输入起始页和终止页来自定义获取想要获取的页数
startpage = int(input('请输入要获取到起始页数>>'))
endpage = int(input('请输入终止页数>>'))
7写for循环对我们输入的范围进行遍历,构造请求头,并利用PyQuary()解析获取的网页数据
for i in range(startpage, endpage):
new_url = base_url + f"koubei-{i + 1}.html"
response = requests.get(url=new_url, headers=headers, proxies=proxies)
response.encoding = response.apparent_encoding
content = response.text
# print(content) 可以打印输出看看有没有获取到
source = PyQuery(content)
8页面分析
可以看出橘色框的.cm-content-box类的div标签包含了页面中的所有车评,即类名为 cm-content-moudle 的div标签,接下来就是进一步细分所提取的数据包含在哪个标签之中,不再描述,如果对pyquery语法没有基础认知请先过一遍基础语法
9 逐个获取数据
for item in targetblock:
# print(item)
# 1用户名
username = item('.cm-user-name').text()
# print(username)
# 2评论日期
comm_date = item('.cm-user-panel p span').text()
# print(comm_date)
# 3车型
car_type = item('.cm-car-name').text()
# print(car_type)
# 4评分
score = item('.score').text()
# print(score)
# 5裸车价
car_price = item('.cm-car-price-value').text()
# print(car_price)
# 6油耗
oil = item('.cm-car-oil-value').text()
# print(oil)
# 7购车时间
buy_time = item('.cm-car-buy-time-value').text()
# print(buy_time)
# 8 评价内容
comment = item('.cm-content p').text()
# print(comment)
10 定义数据列表将数据输出并保存为csv文件
info_all = [username, comm_date, car_type, score, car_price, oil, buy_time, comment]
writer.writerow(info_all)
print(info_all)
11运行与结果