首页 >> 大全

python爬虫 javascript动态数据 携程旅游 含源码

2024-01-01 大全 34 作者:考证青年

数据源分析

本次练手的网站是携程,主题是欧洲游,进入目标页面,点击js插件。没有的朋友可以去装一个。也可以设置浏览器关闭js

原界面

禁用js后的界面

携程脚本__爬取携程数据

很多重要信息都不见了,这些内容就是js动态加载的。

上面我用的浏览器是火狐,因为装插件比较方便,下面换谷歌浏览器,分析方便。

目标界面-右键检查

在下面选择彩蛋

然后点击上面的刷新,拖动右边的长方形,拉到最下面,这样数据才能完全加载。

数据加载好后点击name排序,下面的文件都是刷新后加载的。找到我们要的数据文件。

可以看到储存在一个文件中,是文件的人性化格式。

接下来就是获取这个文件了。爬虫原理就是模拟浏览器浏览。

点击查看文件的请求信息.。

携程脚本__爬取携程数据

_爬取携程数据_携程脚本

本次主要使用一下信息。翻译一下就会明白都是什么

headers = {'Accept': 'application/json, text/javascript, */*; q=0.01','Accept-Language': 'zh-CN,zh;q=0.9','Cache-Control': 'no-cache','User-Agent':' Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36','Connection': 'keep-alive','Referer': 'http://vacations.ctrip.com/tours/r-europe-120002'}

还需要一个,有这些信息就可以获取js加载的文件了。

formdata = {
'params': [{"Id":1606014,"Bu":"GT","Did":1},{"Id":1742175,"Bu":"GT","Did":1},           {"Id":1729325,"Bu":"GT","Did":1},{"Id":19825554,"Bu":"GT","Did":1},{"Id":1606014,"Bu":"GT","Did":1}],
'keyword': '欧洲'
}

单个文件获取代码

# -*- coding: utf-8 -*-
import json
import urllib
import urllib2
import reurl = "http://vacations.ctrip.com/tour-mainsite-vacations/api/product"
headers = {'Accept': 'application/json, text/javascript, */*; q=0.01','Accept-Language': 'zh-CN,zh;q=0.9','Cache-Control': 'no-cache','User-Agent':' Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36','Connection': 'keep-alive','Referer': 'http://vacations.ctrip.com/tours/r-europe-120002'}
formdata = {
'params': [{"Id":0,"Bu":"GT","Did":1}],
'keyword': '欧洲'
}
formdata['params'][0]['Id'] = 1979857data = urllib.urlencode(formdata)
request = urllib2.Request(url,data = data,  headers = headers)
response = urllib2.urlopen(request)
value = json.loads(response.read())
pattern = re.compile(r'\d+')for item in value:print item["AdvanceBookingDays"] #观光天数print item["DepartureCityName"]  #出发城市名称print item["DestinationName"]    #目的地名称print pattern.search(item["Price"]).group()  #价格print item["ScheduleDesc"]       #班期print item["VendorName"]         #供应商名称print item["TravelCount"]        #观光客数量print item["Score"]              #评分print item["CommentCount"]       #点评数量

*然后这篇博客就结束啦,博主可以玩游戏啦?

当然没有,细心的小伙伴应该发现问题了,就是每个文件的是不同的。

每个都包含了或多或少的json对象,每个对象都包含一个长长的不唯一的Id属性,聪明的小伙伴应该猜到了每一个json对象对应上面的一个旅游信息,那么这个Id是我的浏览器生成的吗,肯定不是,数据都是服务器传过来的。

进一步解析页面

用选择器选择旅游div,看他的源码,有一个叫data-的属性包含了Id信息,而这个属性就在我们选中的div中。

幸好这一部分是静态的,我们获取。首先创建一个项目,下面源码

item.py

# -*- coding: utf-8 -*-# Define here the models for your scraped items
#
# See documentation in:
# https://doc.scrapy.org/en/latest/topics/items.htmlimport scrapyclass DazhongItem(scrapy.Item):# define the fields for your item here like:# name = scrapy.Field()pkgid = scrapy.Field()

.py

import scrapy
from scrapy import signals
from scrapy.downloadermiddlewares.useragent import UserAgentMiddleware
import randomclass MyUserAgentMiddleware(UserAgentMiddleware):def __init__(self, user_agent):self.user_agent = user_agent@classmethoddef from_crawler(cls,crawler):return cls(user_agent = crawler.settings.get('MY_USER_AGENT'))def process_request(self, request, spider):agent = random.choice(self.user_agent)request.headers['User-Agent'] = agent

.py

# -*- coding: utf-8 -*-
import scrapy
# Scrapy settings for dazhong project
#
# For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation:
#
#     https://doc.scrapy.org/en/latest/topics/settings.html
#     https://doc.scrapy.org/en/latest/topics/downloader-middleware.html
#     https://doc.scrapy.org/en/latest/topics/spider-middleware.htmlBOT_NAME = 'DzdpCrawl'SPIDER_MODULES = ['DzdpCrawl.spiders']
NEWSPIDER_MODULE = 'DzdpCrawl.spiders'# Crawl responsibly by identifying yourself (and your website) on the user-agent
MY_USER_AGENT = ["Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; AcooBrowser; .NET CLR 1.1.4322; .NET CLR 2.0.50727)","Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; Acoo Browser; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; .NET CLR 3.0.04506)","Mozilla/4.0 (compatible; MSIE 7.0; AOL 9.5; AOLBuild 4337.35; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)","Mozilla/5.0 (Windows; U; MSIE 9.0; Windows NT 9.0; en-US)","Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET CLR 2.0.50727; Media Center PC 6.0)","Mozilla/5.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET CLR 1.0.3705; .NET CLR 1.1.4322)","Mozilla/4.0 (compatible; MSIE 7.0b; Windows NT 5.2; .NET CLR 1.1.4322; .NET CLR 2.0.50727; InfoPath.2; .NET CLR 3.0.04506.30)","Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN) AppleWebKit/523.15 (KHTML, like Gecko, Safari/419.3) Arora/0.3 (Change: 287 c9dfb30)","Mozilla/5.0 (X11; U; Linux; en-US) AppleWebKit/527+ (KHTML, like Gecko, Safari/419.3) Arora/0.6","Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.2pre) Gecko/20070215 K-Ninja/2.1.1","Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9) Gecko/20080705 Firefox/3.0 Kapiko/3.0","Mozilla/5.0 (X11; Linux i686; U;) Gecko/20070322 Kazehakase/0.4.5","Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.8) Gecko Fedora/1.9.0.8-1.fc10 Kazehakase/0.5.6","Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11","Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_3) AppleWebKit/535.20 (KHTML, like Gecko) Chrome/19.0.1036.7 Safari/535.20","Opera/9.80 (Macintosh; Intel Mac OS X 10.6.8; U; fr) Presto/2.9.168 Version/11.52","Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.11 TaoBrowser/2.0 Safari/536.11","Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.71 Safari/537.1 LBBROWSER","Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; LBBROWSER)","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; QQDownload 732; .NET4.0C; .NET4.0E; LBBROWSER)","Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.84 Safari/535.11 LBBROWSER","Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E)","Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; QQBrowser/7.0.3698.400)","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; QQDownload 732; .NET4.0C; .NET4.0E)","Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; SV1; QQDownload 732; .NET4.0C; .NET4.0E; 360SE)","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; QQDownload 732; .NET4.0C; .NET4.0E)","Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E)","Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.89 Safari/537.1","Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.89 Safari/537.1","Mozilla/5.0 (iPad; U; CPU OS 4_2_1 like Mac OS X; zh-cn) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8C148 Safari/6533.18.5","Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:2.0b13pre) Gecko/20110307 Firefox/4.0b13pre","Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:16.0) Gecko/20100101 Firefox/16.0","Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11","Mozilla/5.0 (X11; U; Linux x86_64; zh-CN; rv:1.9.2.10) Gecko/20100922 Ubuntu/10.10 (maverick) Firefox/3.6.10","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36",]# Obey robots.txt rules
ROBOTSTXT_OBEY = False
# Configure maximum concurrent requests performed by Scrapy (default: 16)
#CONCURRENT_REQUESTS = 32# Configure a delay for requests for the same website (default: 0)
# See https://doc.scrapy.org/en/latest/topics/settings.html#download-delay
# See also autothrottle settings and docs
DOWNLOAD_DELAY = 10
# The download delay setting will honor only one of:
#CONCURRENT_REQUESTS_PER_DOMAIN = 16
#CONCURRENT_REQUESTS_PER_IP = 16# Disable cookies (enabled by default)
#COOKIES_ENABLED = False# Disable Telnet Console (enabled by default)
#TELNETCONSOLE_ENABLED = False# Override the default request headers:
#DEFAULT_REQUEST_HEADERS = {
#   'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
#   'Accept-Language': 'en',
#}# Enable or disable spider middlewares
# See https://doc.scrapy.org/en/latest/topics/spider-middleware.html
#SPIDER_MIDDLEWARES = {
#    'dazhong.middlewares.DazhongSpiderMiddleware': 543,
#}# Enable or disable downloader middlewares
# See https://doc.scrapy.org/en/latest/topics/downloader-middleware.html
DOWNLOADER_MIDDLEWARES = {'scrapy.downloadermiddleware.useragent.UserAgentMiddleware': None,'scrapy.downloadermiddlewares.useragent.UserAgentMiddleware': None,'DzdpCrawl.middlewares.MyUserAgentMiddleware': 400,
}# Enable or disable extensions
# See https://doc.scrapy.org/en/latest/topics/extensions.html
#EXTENSIONS = {
#    'scrapy.extensions.telnet.TelnetConsole': None,
#}# Configure item pipelines
# See https://doc.scrapy.org/en/latest/topics/item-pipeline.html
ITEM_PIPELINES = {
'DzdpCrawl.pipelines.DazhongPipeline': 300,
}# Enable and configure the AutoThrottle extension (disabled by default)
# See https://doc.scrapy.org/en/latest/topics/autothrottle.html
#AUTOTHROTTLE_ENABLED = True
# The initial download delay
#AUTOTHROTTLE_START_DELAY = 5
# The maximum download delay to be set in case of high latencies
#AUTOTHROTTLE_MAX_DELAY = 60
# The average number of requests Scrapy should be sending in parallel to
# each remote server
#AUTOTHROTTLE_TARGET_CONCURRENCY = 1.0
# Enable showing throttling stats for every response received:
#AUTOTHROTTLE_DEBUG = False# Enable and configure HTTP caching (disabled by default)
# See https://doc.scrapy.org/en/latest/topics/downloader-middleware.html#httpcache-middleware-settings
#HTTPCACHE_ENABLED = True
#HTTPCACHE_EXPIRATION_SECS = 0
#HTTPCACHE_DIR = 'httpcache'
#HTTPCACHE_IGNORE_HTTP_CODES = []
#HTTPCACHE_STORAGE = 'scrapy.extensions.httpcache.FilesystemCacheStorage'

.py

# -*- coding: utf-8 -*-
from openpyxl import Workbookclass DazhongPipeline(object):  # 设置工序一def __init__(self):self.wb = Workbook()self.ws = self.wb.activeself.ws.append(['pkgid'])  # 设置表头def process_item(self, item, spider):  # 工序具体内容line = [item['pkgid']]  # 把数据中每一项整理出来self.ws.append(line)  # 将数据以行的形式添加到xlsx中self.wb.save('pkgid.xlsx')  # 保存xlsx文件return itemdef spider_closed(self, spider):self.file.close()

.py

# -*- coding: utf-8 -*-
import scrapy
import re
from bs4 import BeautifulSoup
from scrapy.http import Request
from ..items import DazhongItem
import json
import xlrd
import xlwt
from xlutils.copy import copyclass DzSpider(scrapy.Spider):name = 'dz'allowed_domains = ['vacations.ctrip.com']first_url = 'http://vacations.ctrip.com/tours/r-europe-120002/'last_url = 'p'filename = 'D:\python\DzdpScrpy\Allpkgid.json'list = []def start_requests(self):for i in range(1,101):url = self.first_url + self.last_url + str(i)yield Request(url,self.parse)def parse(self, response):soup = BeautifulSoup(response.body,'lxml')item = DazhongItem()for site in soup.find_all('div',class_='main_mod product_box flag_product '):try:str =  site.attrs['data-tracevalue']json_1 = json.loads(str)item['pkgid'] = json_1['pkgid']yield itemexcept:pass

结果:

携程脚本__爬取携程数据

这下Id有了,接下来就是获取数据了。把Id从Excel表格中迭代出来,可以选择生成一个巨大的,也可已从下面赋值,一个一个地取

Excel表格的操作可以看我的另一篇文章。

有问题留言,我尽力帮助

祝爬虫顺利~~~

关于我们

最火推荐

小编推荐

联系我们


版权声明:本站内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 88@qq.com 举报,一经查实,本站将立刻删除。备案号:桂ICP备2021009421号
Powered By Z-BlogPHP.
复制成功
微信号:
我知道了