Python全系列 教程
3567个小节阅读:5931.1k
目录
鸿蒙应用开发
C语言快速入门
JAVA全系列 教程
面向对象的程序设计语言
Python全系列 教程
Python3.x版本,未来主流的版本
人工智能 教程
顺势而为,AI创新未来
大厂算法 教程
算法,程序员自我提升必经之路
C++ 教程
一门通用计算机编程语言
微服务 教程
目前业界流行的框架组合
web前端全系列 教程
通向WEB技术世界的钥匙
大数据全系列 教程
站在云端操控万千数据
AIGC全能工具班
A A
White Night
x1import scrapy
2from json import loads
3
4class PiaoSpider(scrapy.Spider):
5 name = "piao"
6 allowed_domains = ["piao.qunar.com"]
7 start_urls = ["https://touch.piao.qunar.com/touch/toNewCityList.htm"]
8 url = 'https://touch.piao.qunar.com/touch/list.json?region={city}&isForeign=false&page={pn}&pageSize=60&keyword=%E6%99%AF%E7%82%B9%E9%97%A8%E7%A5%A8'
9 def parse(self, response):
10
11 # 提示所有城市信息 第一个xpath是定义热门城市,第二个是定位境内的城市
12 all_city = response.xpath('//ul[@class="mp-list mp-tr3"]')[0].xpath('./li/a/text()').extract()
13 for city in all_city:
14 yield scrapy.Request(self.url.format(city=city,pn=1), callback=self.parse_page,meta={'city':city})
15
16 def parse_page(self,response):
17 # 将字符串数据转换为字典数据
18 resp = loads(response.text)
19 # 获取数据列表
20 sight_list = resp.get('data').get('sightList')
21 # 遍历列表,获取每个景点的信息
22 for item in sight_list:
23 data = {
24 'name':item.get('name'),
25 'level':item.get('level'),
26 'city':item.get('hybridAddress'),
27 'address':item.get('address'),
28 'price':item.get('qunarPrice'),
29 'comment':item.get('commentCount'),
30 'sight_commentScore':item.get('sightCommentScore')
31 }
32 # 将数据推送到管道
33 yield data
34 # 获取数据总数
35 total = resp.get('data').get('totalCount')
36 # 获取要爬取的城市
37 city = response.meta.get('city')
38 # 获取总页数
39 page = (total + 60-1 )//60
40 # 判断page是否大于1
41 if page > 1:
42 count = 1
43 for pn in range(2,int(page)+1):
44 if count > 3:
45 break
46 print(f'正在获取{city},第{pn}页数据')
47 yield scrapy.Request(self.url.format(city=city,pn=pn), callback=self.parse_info)
48 count += 1
49
50 def parse_info(self,response):
51 # 将字符串数据转换为字典数据
52 resp = loads(response.text)
53 # 获取数据列表
54 sight_list = resp.get('data').get('sightList')
55 # 遍历列表,获取每个景点的信息
56 for item in sight_list:
57 data = {
58 'name':item.get('name'),
59 'level':item.get('level'),
60 'city':item.get('hybridAddress'),
61 'address':item.get('address'),
62 'price':item.get('qunarPrice'),
63 'comment':item.get('commentCount'),
64 'sight_comment_score':item.get('sightCommentScore')
65 }
66 yield data