爬虫 汽车之家,-新汽车信息多页爬虫程序代码QZQ - get(url=url, headers=headers, timeout=10)
import requests
import pandas as pd
import time
import parsel
import re
# 创建一个列表存储所有数据
car_data = []
# 定义爬取单页数据的函数
def crawl_page(page_num):
# 构造带页码的URL
if page_num == 1:
url = f'https://www.che168.com/china/list/'
else:
url = f'https://www.che168.com/china/list/{page_num}/'
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36 Edg/140.0.0.0",
"Referer": "https://www.che168.com/china/benchi/"
}
try:
res = requests.get(url=url, headers=headers, timeout=10)
res.raise_for_status() # 检查请求是否成功
res.encoding = res.apparent_encoding # 自动识别编码
selector = parsel.Selector(res.text)
lis = selector.css('.tp-cards-tofu .cards-li.list-photo-li')[:-1]
print(f"正在爬取第{page_num}页,共{len(lis)}条数据")
for i in lis:
# 获取车辆名称信息
name_text = i.css('.card-name::text').get()
if name_text:
ti = name_text.split(' ')
else:
ti = []
continue # 跳过没有名称的条目
# 处理车辆信息
if 'Model' in ti:
pp = ' '.join(ti[:2]) if len(ti) >= 2 else ''
cnf = ti[2] if len(ti) >= 3 else ''
ks = ' '.join(ti[3:]) if len(ti) >= 4 else ''
else:
pp = ti[0] if len(ti) >= 1 else ''
cnf = ti[1] if len(ti) >= 2 else ''
ks = ti[2] if len(ti) >= 3 else ''
# 获取车辆详细信息
unit_text = i.css('.cards-unit::text').get()
if unit_text:
unit_parts = unit_text.split('/')
else:
unit_parts = []
info = unit_parts[0] if len(unit_parts) >= 1 else ''
sp = unit_parts[1] if len(unit_parts) >= 2 else ''
cs = unit_parts[2] if len(unit_parts) >= 3 else ''
hy = unit_parts[3] if len(unit_parts) >= 4 else ''
# 获取价格信息
pi = i.css('.pirce em::text').get() or ''
yj = i.css('a .cards-price-box s::text').get() or ''
# 构建数据字典
dit = {
'品牌': pp,
'年份': cnf,
'款式': ks,
'里程': info,
'上牌时间': sp,
'城市': cs,
'会员': hy,
'售价': pi,
'原价': yj,
'页码': page_num # 记录数据来自哪一页
}
car_data.append(dit) # 将数据添加到列表
return True # 页面爬取成功
except Exception as e:
print(f"爬取第{page_num}页时出错: {str(e)}")
return False # 页面爬取失败
# 爬取多页数据
total_pages = 5 # 要爬取的总页数,可以根据需要修改
for page in range(1, total_pages + 1):
success = crawl_page(page)
if not success:
print(f"第{page}页爬取失败,尝试重新爬取...")
# 重试一次
time.sleep(2)
crawl_page(page)
# 每爬完一页,休眠一段时间,避免给服务器造成过大压力
if page < total_pages:
time.sleep(3) # 可以根据实际情况调整休眠时间
# 将数据转换为DataFrame并保存为CSV 拼多多帮助力入口
df = pd.DataFrame(car_data)
df.to_csv('汽车数据_多页.csv', index=False, encoding='utf-8-sig')
print(f"数据已保存到汽车数据_多页.csv,共{len(car_data)}条记录"),爬虫