Python爬虫学习(一)12306余票信息爬取
环境介绍
IDE:PyCharm Community.
Python 编译器 3.6
实现步骤
1.12306有反爬取机制,余票信息是在网页就绪以后异步加载出来的,首先我们可以打开谷歌浏览器找到,找到中间请求的URL,例如余票检索按钮单击的时候https://kyfw.12306.cn/otn/leftTicket/query?leftTicketDTO.train_date=2017-12-25&leftTicketDTO.from_station=ZZF&leftTicketDTO.to_station=XXF&purpose_codes=ADULT
由上图可知,余票信息是放在result里面的
2.取得这些数据
req = urllib.request.Request(html) req.add_header('User-Agent', '/Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML like Gecko) Chrome/59.0.3071.115 Safari/537.36') html = urllib.request.urlopen(req).read() aaa = json.loads(html) result = aaa['data']['result']
for i in getList(html): info = i.split('|') print('车次:%s' % (info[3])) print('出发时间 :%s' % (info[8])) print('到达时间 :%s' % (info[9])) print('硬卧 :%s' % (info[28])) print('二等座 :%s' % (info[30])) print('-----------------------')
再解析出来就OK了
源码已经上传到****上面了,
http://download.****.net/download/baidu_29609961/10169706