python爬取火车票网的时刻表数据

python爬取火车票网的时刻表数据

导包

**
import re,requests,datetime,time,json
from prettytable import PrettyTable
from colorama import init,Fore
from pyquery import PyQuery as pq
import random
import pymysql.cursors
**

导包遇到问题的解决方法

1.在pycharm中: File ——> Setting——>Project Interpreter,在package一栏最后有个加号,点进去搜requests下载就可以了。

2.方法1没解决的话,打开cmd输入cd进入你的python运行环境script文件夹的位置,例如:cd D://python//python37//script,然后输入:pip install requests(举例requests模块,其它也可)。

3,方法1和方法2还未解决的话,下载你要导入模块相应的whl文件,whl文件链接地址:python的whl文件下载,下载后存到:E://pythonWhl(举例),然后打开cmd输入cd进入你的python运行环境script文件夹的位置,例如:cd C://python//python37//script,然后输入:pip install E://pythonWhl//.whl,下载完whl文件后再pip install requests(举例requests模块,其它也可)就可以了。

4.如果方法1,2,3都没用,建议重新启动,或者检查网络,我在下pyMySQL模块时三个方法都用了还是不行,结果第二天打开 File ——> Setting——>Project Interpreter找到pyMySQL模块下载成功了,哈哈哈哈。

代码

# -*- coding: utf-8 -*-
import re,requests,datetime,time,json
from prettytable import PrettyTable
from colorama import init,Fore
from pyquery import PyQuery as pq
import random
import pymysql.cursors

# 关闭https证书验证警告
requests.packages.urllib3.disable_warnings()

init(autoreset=False)

# 全局变量,每增加一次加1
sta_num=1#记录station表的增加次数
tra_num=1#记录train表的增加次数

#取每一辆车的具体信息
def showTrainInfo(train_name,conn):
	#打印传过来的火车名
    print(train_name)
    # 获取数据执行cursor
    cursor=conn.cursor()
    # 获取url
    url="http://search.huochepiao.com/chaxun/resultc.asp?txtCheci={}&cc.x=60&cc.y=8".format(train_name)
    # 获取头信息
    header = {
    	#在自己的浏览器打开F12随便找一个request Header里面就有
        "User-Agent": ""
    }
    try:
        # 获取链接
        r = requests.get(url, headers=header)
        # 设置编码格式
        r.encoding = r.apparent_encoding
        # 获取页面中的html并解析
        doc = pq(r.text)
        # 获取所有table中的tr
        trs = doc('tr')
        # 定义train表的字段
        trian_num, running_time, station_start, station_end, start_time, arrival_time, train_type, mileage, version_date = '', '', '', '', '', '', '', '', ''
        # 循环获取每一个tr
        for tr in trs:
            # 时刻表
            if len(tr) == 12 or len(tr) == 13:
                if tr[0].text_content()!='车次' and tr[0].text_content()!="":
                    global sta_num
                    sql_1 = "insert into station values({},'{}','{}','{}','{}','{}','{}','{}','{}','{}')".format(sta_num,tr[0].text_content(),tr[1].text_content(),tr[2].text_content(),tr[3].text_content(),tr[4].text_content(),tr[5].text_content(),tr[6].text_content(),tr[7].text_content(),tr[8].text_content())
                    # print('车次:', tr[0].text_content(), ',站次:', tr[1].text_content(), ',站名:', tr[2].text_content(), ',到达时间:',
                    #       tr[3].text_content(), ',开车时间:', tr[4].text_content(), ',停留时间:', tr[5].text_content(), ',运行时间:',
                    #       tr[6].text_content(), ',天数:', tr[7].text_content(), ',里程:',tr[8].text_content())
                    print(sql_1)
                    cursor.execute(sql_1)
                    sta_num+=1
                else:
                    continue
            elif 3<len(tr)<12:
                # train组装
                if tr[1].text_content()=='站站查询':
                    continue
                elif tr[1].text_content()=='车次':
                    trian_num =tr[2].text_content()
                    running_time=tr[4].text_content()
                    # print("车次:",tr[2].text_content())
                    # print("运行时间:", tr[4].text_content())
                    # pass
                elif tr[0].text_content() == '始发站':
                    # print("始发站:", tr[1].text_content())
                    # print("终点站:", tr[3].text_content())
                    station_start=tr[1].text_content()
                    station_end=tr[3].text_content()
                    # pass
                elif tr[0].text_content() == '发车时间':
                    # print("发车时间:", tr[1].text_content())
                    # print("到站时间:", tr[3].text_content())
                    start_time=tr[1].text_content()
                    arrival_time=tr[3].text_content()
                    # pass
                elif tr[0].text_content() == '类型':
                    # print("类型:", tr[1].text_content())
                    # print("全程:", tr[3].text_content())
                    train_type=tr[1].text_content()
                    mileage=tr[3].text_content()
                    # pass
                else:
                    # pass
                    varsion_date=tr[0].text_content()
                    # print("版本日期:",tr[0].text_content())
            else:
                continue
        if  trian_num!="":
        	#声明全局变量
            global tra_num
            sql_2 = "insert into train values({},'{}','{}','{}','{}','{}','{}','{}','{}','{}','运行中')".format(tra_num,trian_num, running_time,station_start, station_end,start_time, arrival_time,train_type, mileage,version_date)
            print(sql_2)
            cursor.execute(sql_2)
            tra_num+=1
        conn.commit()
    except  Exception as e:
        print("错误原因:",e)
        showTrainInfo(train_name)

def main():
    # 获取数据连接
    #host:本地数据库主机名或云数据库的主机名
    #port:MySQL的端口号(一般3306)
    #user:MySQL的用户名
    #passwd:MySQL的密码
    #db:要链接的库名
    conn = pymysql.connect(host="", port=, user="", passwd="", db="")
    # 以下是测试
    # 获取执行者cursor
    # cursor = conn.cursor()
    # sql = "insert into station values(null,'3','3','3','3','3','3','3')"
    # cursor.execute(sql)
    # conn.commit()


    # 查询车次,总共446页,获取每一页的数据
    for i in range(1,447):
        print(i)
        # 获取url
        url = "http://search.huochepiao.com/update/bianhao/?p={}&key=".format(i)
        # 设置头信息
        header = {
       	 #在自己的浏览器打开F12随便找一个request Header里面就有
         "User-Agent": ""
        }
        try:
            # 获取链接
            r = requests.get(url, headers=header)
            # 设置编码格式
            r.encoding = r.apparent_encoding
            # 获取页面中的html并解析
            doc = pq(r.text)
            # 获取所有table中的tr
            trs = doc('tr')
            # 循环获取每一个tr
            for tr in trs:
                # 如果这一行长度不是5也去掉,只取车次名
                if len(tr) == 5:
                    # 如果这一行开头不是车次
                    if tr[0].text_content() != '车次':
                        # print(tr[0].text_content())
                        showTrainInfo(tr[0].text_content(),conn)#车次名、数据库连接、cursor作为参数
                    else:
                        continue
                else:
                    continue
        except Exception as e:
            print("错误原因:", e)
            i=i-1
            continue
    conn.close()#关闭数据库资源
    print("恭喜你,完成了!!!")
main()

注意

1.数据库以及对应的表要建好
2.我当时爬完所有数据花了3、4个小时,train表有7146条数据,station表有83809条数据
3.我用的python是2019.02.06版本,环境是python37
4.train表的version_date爬的数据后面很多空值,而且前面都是版本日期+时间,建议爬完所有后在数据库修改:update train set version_date=‘2020/03/05’(举例)

猜你喜欢

转载自blog.csdn.net/Inmaturity_7/article/details/106034971