不少人学习python,不知道从何学起。
不少人学习python,掌握了基本语法事后,不知道在哪里寻找案例上手。
不少已经作案例的人,殊不知道如何去学习更加高深的知识。
那么针对这三类人,我给你们提供一个好的学习平台,免费领取视频教程,电子书籍,以及课程的源代码!
QQ群:1097524789html
基本的原理都已经了解了 ,那我们不整一下,咋行?光说不练假把式,走起!!!python
本节源码:[仓库地址]( https://github.com/Mr2753/PythonScrape/tree/master/GuaZI_Car )git
首先先说一下基本的思路:github
本次请求的URL(先放地址了!)编程
根据以上可知,URL:https://www.guazi.com/{cs}/buy/o{page}/#bread ,更具改变cs改变城市,一线城市为前拼音两个字母(例如:长沙/cs 、湘潭/xiangtan),第一页为o1,第二个为o2。以此类推并发
发送请求:异步
1async 2post 3 4 5 |
async def scrape(self, url): async with self.semaphore: async with aiohttp.ClientSession(headers=self.header).get(url) as response: await asyncio.sleep(1) return await response.text() |
注意:再次加入请求头,本网站对Cookies有严格的检测。且并不能挂IP代理访问
解析响应:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
async def parse(self, html): with open('car.csv', 'a+', encoding='utf-8') as f: doc = pq(html) for message in doc('body > div.list-wrap.js-post > ul > li > a').items(): # 汽车简介 car_name = message('h2.t').text() # 汽车详情(年限、里程、服务) car_info = message('div.t-i').text() year = car_info[:5] mileage = car_info[6:-5] service = car_info[13:].replace('|', '') # 价格 try: price = message('div.t-price > p').text() except AttributeError: price = message('em.line-through').text() car_pic = message('img').attr('src') data = f'{car_name}, {year},{mileage}, {service}, {price}n' logging.info(data) f.write(data) |
我这里是直接一步到位了,解析响应,以及保存数据。
运行以后便可看到相似于这样的东东
若有疑问,我们评论区见