python实现简单爬虫

版权声明:尊重原创 https://blog.csdn.net/qq_40163092/article/details/87102404

第一步 准备环境
1.1安装selenium
cmd窗口进入到解压的selenium的目录
输入命令 python setup.py install 进行安装

1.2 配置Chrome浏览器驱动
	将Chromedriver.exe放入Chrome安装目录下,再把Chrome安装路径加入环境变量中  注意Chromedriver.exe 要和Chrome的版本保持对应
1.3完整代码
import requests
import re
from selenium import webdriver
import csv
import time
#tplt = "{:5}\t{:3}\t{:3}\t{:5}\t{:5}\t{:5}\t{:4}\t{:7}\t{:9}\t{:9}\t{:12}\t{:16}\t{:6}\t{:16}\t{:6}\t{:6}\t{:6}\t{:6}"
#tplt_txt = "{:5}\t{:3}\t{:3}\t{:5}\t{:5}\t{:5}\t{:4}\t{:7}\t\t{:9}\t{:9}\t{:12}\t{:16}\t{:6}\t{:16}\t{:6}\t{:6}\t{:6}\t{:6}"
tplt = "{:5}\t{:3}\t{:3}\t{:5}\t{:5}\t{:5}\t{:4}\t{:7}\t{:3}\t{:3}\t{:4}\t{:6}\t{:2}\t{:6}\t{:2}\t{:2}\t{:2}\t{:2}"
tplt_txt = "{:5}\t{:3}\t{:3}\t{:5}\t{:5}\t{:5}\t{:4}\t{:7}\t\t{:3}\t{:3}\t{:4}\t{:6}\t\t{:2}\t{:6}\t\t{:2}\t{:2}\t{:2}\t{:2}"
#格式化输出的表格
ticket_id=[] #爬取到的票的ID,用于构建后面的CSS选择器
def parsePage(html):
    try:
        pattern = re.compile('<tr id="ticket_(.*?)"',re.S)#正则表达式,用于爬取票的ID
        tickets = re.findall(pattern, html)
        for ticket in tickets:
            ticket_id.append(ticket)#加入到全局变量中,方便以后调用
    except:
        print("")
def main():
    start_url = 'https://kyfw.12306.cn/otn/leftTicket/init?linktypeid=dc'#查询火车票的URL
    driver=webdriver.Chrome("D:\\12306Python\\Google\\Chrome\\Application\\chromedriver.exe") #打开Chrome浏览器
    driver.get(start_url)
    time.sleep(2)
    start_station=driver.find_element_by_css_selector('#fromStationText') #找到起点站的输入框
    time.sleep(1)
    start_station.click()#点击输入框
    time.sleep(2)
    start_station.send_keys('郑州')#输入‘郑州’
    time.sleep(2)
    start_station.send_keys('\ue007')#输入回车

    time.sleep(2)
    end_station = driver.find_element_by_css_selector('#toStationText')#找到终点站的输入框
    time.sleep(1)
    end_station.click()#点击输入框
    time.sleep(2)
    end_station.send_keys('上海')#输入‘上海’
    time.sleep(2)
    end_station.send_keys('\ue007')#输入回车
    time.sleep(1)

    choose_date=driver.find_element_by_css_selector('#date_icon_1')#找到日期选择的地方
    time.sleep(1)
    choose_date.click()#点击
    time.sleep(1)
    choose_date1=driver.find_element_by_css_selector(
        'div.cal:nth-child(1) > div:nth-child(3) > div:nth-child(20) > div:nth-child(1)')#找到1月20号
    time.sleep(1)
    choose_date1.click()#点击
    time.sleep(2)
    query=driver.find_element_by_css_selector('#query_ticket')#找到查询按钮
    time.sleep(1)
    # query_ticket
    query.click()#点击
    time.sleep(2)
    train_num_elem=driver.find_element_by_css_selector('#sear-result > p:nth-child(2)')#找到票的总量

    print(train_num_elem.text)#输出
    with open('列车信息.txt', 'w', encoding='utf-8') as file:
        file.write(train_num_elem.text)#写到文件中
        file.write('\n')#写入回车
    time.sleep(3)
    table=driver.find_element_by_css_selector('#queryLeftTable').get_attribute('innerHTML')#找到火车票表的隐藏HTML代码
    parsePage(table)#调用parsePage函数用正则表达式去爬取
    with open('列车信息.txt', 'a',encoding='utf-8') as file:
        file.write(tplt.format('车次', '出发站','到达站','出发时间','到达时间','历时','到达情况','商务座/特等座','一等座','二等座'
            , '高级软卧','软卧/一等座','动卧','硬卧/二等座','软座','硬座','无座','其他'))#按照格式输出抬头
        file.write('\n')#输入回车
    for i in range(len(ticket_id)):
        css_ticket='#ticket_'+ticket_id[i]#用爬取的票的ID构建每个票的CSS选择器
        #css_price='#price_'+ticket_id[i]
        ticket_info=driver.find_element_by_css_selector(css_ticket).text.split('\n')#获取每个票的整个信息,按照\n分割
        final_ticket_info=ticket_info[:-1]+ticket_info[-1].split(' ')[:-1]
        #把获取的列表舍去最后一个元素,最后一个再按空格分割,再舍去最后一个,两个加一起就是最终我们要获得的所有信息
        print(final_ticket_info)#输出

        with open('列车信息.txt', 'a',encoding='utf-8') as file:
            file.write(tplt_txt.format(final_ticket_info[0],final_ticket_info[1],final_ticket_info[2],final_ticket_info[3]
                                   ,final_ticket_info[4],final_ticket_info[5],final_ticket_info[6],final_ticket_info[7]
                                   ,final_ticket_info[8],final_ticket_info[9],final_ticket_info[10],final_ticket_info[11]
                                   ,final_ticket_info[12],final_ticket_info[13],final_ticket_info[14],final_ticket_info[15]
                                   ,final_ticket_info[16],final_ticket_info[17]))
            #输入到文件,第0个到第17个元素分别代替:'车次', '出发站','到达站','出发时间','到达时间','历时','到达情况','商务座/特等座','一等座','二等座'
            #, '高级软卧','软卧/一等座','动卧','硬卧/二等座','软座','硬座','无座','其他'
            file.write('\n')

main()

猜你喜欢

转载自blog.csdn.net/qq_40163092/article/details/87102404