【爬虫作业】python爬虫作业——爬取汽车之家

爬取汽车之家期末作业:

代码如下所示:

python 复制代码
import random
import time

import requests  #发送网络请求
import parsel
import csv
# 1.发送网络请求
headers  = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36 Edg/96.0.1054.62',
    'cookie' :'cna=4PnlF84bLHECATzVzKSn1QVt; sca=affb7120; atpsidas=0812ac0d0153e7414eefc32b_1634996188_1; atpsida=341b48c86ac6a1e14421aa46_1640613502_50'
   }
csv_lmy = open('lmy-1.csv',mode='a',encoding='utf-8-sig',newline='')
csv_write = csv.writer(csv_lmy)#将文件以csv的方式保存
csv_write.writerow(['品牌','里程(万公里)','车龄','城市','认证','售价(万元)','原价(万元)','链接','车辆图片',])#将列表写入csv的前一行
for page in range(1,101):
    print(f'------------正在爬取第{page}页----------------------')
    url = f'https://www.che168.com/china/a0_0msdgscncgpi1ltocsp{page}exx0/'
    response = requests.get(url=url , headers = headers)
    # 2。获取数据 网页源代码
    print(response.text)
    lmy_html = response.text
    # 3.解析数据
    selector = parsel.Selector(lmy_html)
    lis = selector.css('.viewlist_ul li')
    for li in lis:
        try:
            name = li.css('.card-name::text').get()    #车名
            unit = li.css('.cards-unit::text').get()    #信息
            kemNumber = unit.split('/')[0]
            years = unit.split('/')[1]
            city = unit.split('/')[2]
            business = unit.split('/')[3]
            pirce = li.css('.pirce em::text').get()   #价格
            yprice = li.css('s::text').get()           #原价
            carinfo = li.css('.carinfo::attr(href)').get() #详情页链接
            img = li.css('img::attr(src)').get()       #图片链接
            #print(name,kemNumber,years,city,business,pirce,yprice,carinfo,img)
            csv_write.writerow([name,kemNumber,years,city,business,pirce,yprice,carinfo,img])
        except:
            pass
相关推荐
小途软件1 小时前
用于机器人电池电量预测的Sarsa强化学习混合集成方法
java·人工智能·pytorch·python·深度学习·语言模型
扫地的小何尚1 小时前
NVIDIA RTX PC开源AI工具升级:加速LLM和扩散模型的性能革命
人工智能·python·算法·开源·nvidia·1024程序员节
wanglei2007082 小时前
生产者消费者
开发语言·python
清水白石0082 小时前
《从零到进阶:Pydantic v1 与 v2 的核心差异与零成本校验实现原理》
数据库·python
昵称已被吞噬~‘(*@﹏@*)’~2 小时前
【RL+空战】学习记录03:基于JSBSim构造简易空空导弹模型,并结合python接口调用测试
开发语言·人工智能·python·学习·深度强化学习·jsbsim·空战
2501_941877982 小时前
从配置热更新到运行时自适应的互联网工程语法演进与多语言实践随笔分享
开发语言·前端·python
酩酊仙人3 小时前
fastmcp构建mcp server和client
python·ai·mcp
且去填词3 小时前
DeepSeek API 深度解析:从流式输出、Function Calling 到构建拥有“手脚”的 AI 应用
人工智能·python·语言模型·llm·agent·deepseek
rgeshfgreh4 小时前
Python条件与循环实战指南
python
rgeshfgreh4 小时前
通达信LC1文件结构解析指南
python