动态网站数据采集 - 去哪儿网火车票查询爬虫

分析

在去哪儿网火车票查询页面,需要用户填写出发站、目的地站、出发时间等信息,然后,点击搜索按钮,
页面通过Ajax获取并显示查询结果数据。

这里写图片描述

这里用Selenium+PhantomJS模拟这一过程。

  1. 通过Selenium加载火车票查询页面,并获取到需要进行数据填充的3个输入框和进行数据提交的搜索按钮;

  2. 模拟填充3个输入框数据,模拟点搜索按钮;

  3. 从浏览器对象中获取到已经渲染完毕的HTML源码,进行解析,提取火车车次等信息;

  4. 将提取到的数据保存到数据库中;

  5. 如果有多页数据,就模拟点击下一页,跳到第3步继续进行(通过递归调用HTML解析方法实现)

源码

# !/usr/bin/env python
# -*- coding:utf-8 -*-

import time
import pymysql
from lxml import etree
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities


class TrainTicketSpider(object):
    """
    使用Selenium库和PhantomJS浏览器,爬取去哪儿网机票信息
    只实现当日单程票查询
    """

    def __init__(self):
        dcap = dict(DesiredCapabilities.PHANTOMJS)
        dcap["phantomjs.page.settings.userAgent"] = ("Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36")
        self.browser = webdriver.PhantomJS(desired_capabilities=dcap)

        self.connection = pymysql.connect(host='localhost',
                                     user='root',
                                     password='123456',
                                     db='mydb',
                                     charset='utf8',  # 不能用utf-8
                                     cursorclass=pymysql.cursors.DictCursor)

    def crawl(self,url):
        self.browser.set_page_load_timeout(30)
        self.browser.get(url)

        self.browser.save_screenshot('1.png')

        # 发车站输入框
        fromStation=self.browser.find_element(By.NAME,'fromStation')
        # 目的地站输入框
        toStation=self.browser.find_element(By.NAME,'toStation')
        # 发车日期输入框
        date=self.browser.find_element(By.NAME,'date')
        # 搜索按钮
        btn_search=self.browser.find_element(By.NAME,'stsSearch')

        fromStation.clear()
        fromStation.send_keys(input('输入发车站>> '))
        fromStation.click()
        toStation.clear()
        toStation.send_keys(input('输入目的地站>> '))
        toStation.click()
        date.clear()
        date.send_keys(input('输入车车日期(格式:2000-01-22)>> '))
        date.click()
        btn_search.click()

        time.sleep(3)
        self.browser.save_screenshot('2.png')

        self.parse(current_page=1)

    def parse(self,current_page):
        html=self.browser.page_source
        HTML=etree.HTML(html)

        # 获取页数
        pages=HTML.xpath('//a[@data-pager]/text()')
        page_count=len(pages)

        # 当前页所有车次的元素列表
        li_list=HTML.xpath('//ul[@class="tbody"]/li')

        for li in li_list:
            # 车次/类型
            TRAIN_NUM=li.xpath('.//h3/text()')[0].strip('\n ')

            print('正在获取车次>>>',TRAIN_NUM)

            # 发站/到站
            start_station=li.xpath('.//div[@class="td col2"][1]/p[@class="start"]/span/text()')[0]
            end_station=li.xpath('.//div[@class="td col2"][1]/p[@class="end"]/span/text()')[0]
            STATION=(start_station+'-'+end_station).strip('\n ')

            # 发站时间/到站时间
            start_time=li.xpath('.//div[@class="td col2"][2]/time[@class="startime"]/text()')[0]
            end_time=li.xpath('.//div[@class="td col2"][2]/time[@class="endtime daytime"]/text()')[0]
            TIME=(start_time+'-'+end_time).strip('\n ')

            # 运行时间
            DURATION=li.xpath('.//time[@class="duration"]/text()')[0].strip('\n ')

            # 参考票价
            prices=[]
            ticket_types=li.xpath('.//p[@class="ticketed"]/text()') # 车票类型列表
            ticket_prices=li.xpath('.//span[@class="price"]/text()')# 车票价格列表
            for type_price in zip(ticket_types,ticket_prices):
                price='{type} {price}¥'.format(type=type_price[0],price=type_price[1])
                prices.append(price)

            # 剩余票量
            nums=[]
            ticket_ps=li.xpath('.//div[@class="td col4"]//p')
            for ticket_p in ticket_ps:
                ticket_num=ticket_p.xpath('./text()')
                if not ticket_num:
                    ticket_num=ticket_p.xpath('./span/text()')
                nums.append(ticket_num)

            # 车票票价和余票数量一一对应
            PRICE_NUMS=''
            for i in zip(prices,nums):
                price_num="{}{}".format(i[0],i[1][0])
                PRICE_NUMS=PRICE_NUMS+price_num+' ,'
            PRICE_NUMS=PRICE_NUMS.strip(',')

            # 保存到MySQL数据库
            self.save(TRAIN_NUM,STATION,TIME,DURATION,PRICE_NUMS)

        # 如果有下一页,点击下一页按钮,继续爬取
        page_count-=current_page
        if page_count:
            current_page+=1
            a_next=self.browser.find_element(By.XPATH,'//a[@data-pager={page}]'.format(page=current_page))
            a_next.click()
            time.sleep(3)

            # 递归调用解析方法
            self.parse(current_page)
        else:
            print('爬取结束')
            # 关闭数据库
            self.connection.close()


    def save(self,train_num,station,time,duration,price_nums):
        """
        保存到MySQL数据库
            create table qunaer(
                id int not null primary key auto_increment,
                train_num varchar(10) not null,
                station varchar(30) not null,
                time varchar(30) not null,
                duration varchar(50) not null,
                price_nums varchar(80) not null,
            );
        """

        with self.connection.cursor() as cursor:
            sql='INSERT INTO qunaer(train_num,station,time,duration,price_nums) VALUES (%s,%s,%s,%s,%s)'
            cursor.execute(sql,(train_num,station,time,duration,price_nums))
        self.connection.commit()


if __name__ == '__main__':
    url='https://train.qunar.com/'
    spider=TrainTicketSpider()
    spider.crawl(url)

运行结果

/usr/bin/python3.5 /home/brandon/PythonProjects/MySpider/2_动态数据采集/selenium与phantomjs/小案例/去哪儿网机票查询爬虫.py
/usr/local/lib/python3.5/dist-packages/selenium/webdriver/phantomjs/webdriver.py:49: UserWarning: Selenium support for PhantomJS has been deprecated, please use headless versions of Chrome or Firefox instead
  warnings.warn('Selenium support for PhantomJS has been deprecated, please use headless '
输入发车站>> 北京
输入目的地站>> 石家庄
输入车车日期(格式:2000-01-22)>> 2015-01-15
正在获取车次>>> K7761
正在获取车次>>> K219
正在获取车次>>> K7725
正在获取车次>>> K599
正在获取车次>>> K7705
正在获取车次>>> G6731
...

这里写图片描述

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值