任何一个伟大的目标,都有一个微不足道的开始。
上天从未抛弃过每一个努力生长的灵魂,也不曾辜负过每一个擦肩而过的生命,所有不期而遇的温暖,悄然改变着那些看似惨淡混沌的人生。
Fork me on github

抓取每路公交的具体信息

@

1.抓取查询路径:

抓取 https://lanzhou.8684.cn/ 中以数字开头的公交线路的查询路径。

<div class="list">
    <a href="/list1">1</a>
    <a href="/list2">2</a>
    <a href="/list3">3</a>
    <a href="/list4">4</a>
    <a href="/list5">5</a>
    <a href="/list6">6</a>
    <a href="/list7">7</a>
    <a href="/list8">8</a>
    <a href="/list9">9</a>
</div>

这里所看到的 href 属性值,加上 https://lanzhou.8684.cn/ 就是将来的查询地址。

以此抓取所有的数字开头的公交线路。:

https://lanzhou.8684.cn/listX

其中末尾的 X 表示 数字 1 ~ 9
如:https://lanzhou.8684.cn/list1

2.拼接每路公交的线路链接:

抓取 https://lanzhou.8684.cn/listX中每路公交的线路链接。

<div class="list clearfix">
	<a href="/x_24f5dad9" title="兰州1路公交车路线">1路</a>
	<a href="/x_8234e473" title="兰州10路公交车路线">10路</a>
	<a href="/x_26ecc8ae" title="兰州11路公交车路线">11路</a>
	<a href="/x_27905c0e" title="兰州12路公交车路线">12路</a>
	<a href="/x_9023980b" title="兰州13路公交车路线">13路</a>
	<a href="/x_be53b447" title="兰州14路公交车路线">14路</a>
	<a href="/x_5a54ae14" title="兰州15路公交车路线">15路</a>
	<a href="/x_968a4331" title="兰州16路公交车路线">16路</a>
	<a href="/x_4177a33a" title="兰州17路公交车路线">17路</a>
	<a href="/x_bfe4a3eb" title="兰州18路公交车路线">18路</a>
	...
</div>

这里所看到的 href 属性值,加上 https://lanzhou.8684.cn/ 就是每路公交的线路链接。
如:https://lanzhou.8684.cn/x_24f5dad9

以此抓取所有线路链接。:

3.抓取每路公交的具体信息

兰州9路公交车路线[市区线路]
运行时间:西关什字6:00-22:30|晟地兰州汽配城6:00-21:40
参考票价:无人售票车,1.0元一票制,支持交联IC卡/云闪付/微信/支付宝/万支付/翼支付/美团支付等多种支付方式
公交公司:兰州公交集团第五客运公司

4. 实现代码

# author:Aurora
# Datetime:2022-6-24 11:41:00
""" 
抓取每路公交的具体信息
title:
run_time:
tickets_price:
bus_company:
"""
# 所有库
import requests
import re
from bs4 import BeautifulSoup
import pandas as pd
import os
import time

# 进度条
def progress():
    for i in range(101):
        time.sleep(0.05)
        print(f"\r进度:{'-'*i} {i}%", end='')
    return 200

# 获取信息函数
def get_every_raod_bus_info():
    url = "https://lanzhou.8684.cn/"
    # 伪造header
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.5005.124 Safari/537.36 Edg/102.0.1245.44"
    }
    response = requests.get(url=url, headers=headers)
    soup = BeautifulSoup(response.text, features='lxml')
    """ 
    兰州公交线路:
    1. 以数字开头
    2. 以汉字/字母开头
    3. 线路分类

    都在三个类为pl10的标签中,获取它们
    """
    # 获取第一个pl10也就就是以数字开头,
    items = soup.select('.pl10')[0]
    # 获取list
    list = items.select('.list')
    list = list[0] if len(list) > 0 else ''
    # 获取list里面的a标签
    a = list.select('a')
    # 获取属性href:['/list','/list2',..,'/list9'],listX,X代表不同数字开头的公家车,1,11,12,119,110路等公交车
    hrefs = [i['href'] for i in a]
    link = "https://lanzhou.8684.cn/"
    # 1. 拼接查询地址https://lanzhou.8684.cn/listX,X[1-9],就是每个数字开头的公公交车
    # 输入数字开头的公交线路(1-9)
    n1 = eval(input("请输入以数字开头的公车(1-9):"))
    links = []
    links.append(link+hrefs[n1-1])
    print(links)

    # 2. 拼接每路公交的线路链接
    """ 
    格式如下
    1:https://lanzhou.8684.cn/x_24f5dad9
    10:https://lanzhou.8684.cn/x_8234e473
    11:https://lanzhou.8684.cn/x_26ecc8ae
    ...
    https://lanzhou.8684.cn/XXXX
    """
    # 每路公交的链接列表
    road_list = []
    # 链接前缀
    all_road_prefix = "https://lanzhou.8684.cn"
    for url in links:
        response = requests.get(url, headers=headers)
        soup = BeautifulSoup(response.text, features='lxml')
        # 获取list
        lists = soup.select('.list')
        list = lists[0] if len(lists) > 0 else ''
        # 获取里面的a标签
        a = list.select('a')
        for i in a:
            # 取属性href然后拼接后存入到road_list
            road_list.append(all_road_prefix+i['href'])
    print(road_list)
    # 3. 获取每路公交的信息
    """ 
    title:
    run_time:
    tickets_price:
    bus_company:
    last_updated:
    """
    road_info_dic = {}
    title_list = []
    run_time_list = []
    ticket_price_list = []
    bus_company_list = []
    last_updated_list = []
    n = 1
    for road_url in road_list:
        response = requests.get(road_url, headers=headers)
        soup = BeautifulSoup(response.text, features='lxml')
        # 获取信息(返回的是列表)
        info = soup.select('.info')
        # print(info)
        # 判断是否为空
        info = info[0] if len(info) > 0 else ''
        # 获取所有span标签
        spans = info.select('span')
        """
        [<span aria-label="兰州1路公交车路线" tabindex="0">兰州1路公交车路线</span>, <span tabindex="0">公交公司:</span>, <span tabindex="0">最后更新:2022-06-24</span>]
        """
        # 标题:兰州1路公交车路线
        title = spans[0].text
        # 获取所有a标签
        a = info.select('a')
        """
        [<a aria-label="市区线路,按回车键查看全部市区线路" class="category" href="/line1">[市区线路]</a>, <a aria-label="兰州公交集团第一客运公司,按回车键查看全部兰州公交
        集团第一客运公司运营的公交线路。" href="/g21" title="兰州公交集团第一客运公司">兰州公交集团第一客运公司</a>]
        """
        # 发现副标题category在第一个a标签里面
        # 副标题:[市区线路]
        categorys = a[0].text
        # 拼接总标题
        # 总标题: 兰州9路公交车路线[市区线路]
        titles = title+categorys
        title_list.append(titles)
        print(titles)
        # 获取所用信息描述:ul标签
        bus_descs = info.select('.bus-desc')
        bus_desc = bus_descs[0] if len(bus_descs) > 0 else ''
        # 获取所有li标签(信息都在li中)如下:
        lis = bus_desc.select('li')
        # print(lis)
        """
        [<li tabindex="0">运行时间:兰州西站5:55-00:00|兰州车站5:40-00:00</li>, <li tabindex="0">参考票价:无人售票车,1.0元一票制,支持交联IC卡/云闪付/微信/支付宝/万支付/
        翼支付/美团支付等多种支付方式</li>, <li><span tabindex="0">公交公司:</span><a aria-label="兰州公交集团第一客运公司,按回车键查看全部兰州公交集团第一客运公司运营的
        公交线路。" href="/g21" title="兰州公交集团第一客运公司">兰州公交集团第一客运公司</a></li>, <li><span tabindex="0">最后更新:2022-06-24</span><div class="wechat-promote tooltip-btn" data--tooltip-align="center" data-tooltip-body="wechatPromote" wbfignoreele=""><i class="iconfont iconwechat"></i>免费发送线路信息到微信</div></li>, <li tabindex="0">※ 本查询结果仅供参考,车程及票价请以实际发生为准</li>]
        """
        # 从lis中获取想要的信息:
        # 1. 运行时间
        run_times = lis[0].text
        run_time_list.append(run_times)
        print(run_times)
        # 2. 参考票价
        tickets_price = lis[1].text
        ticket_price_list.append(tickets_price)
        print(tickets_price)
        # 3. 公交公司
        """
        <li><span tabindex="0">公交公司:</span><a aria-label="兰州公交集团第一客运公司,按回车键查看全部兰州公交集团第一客运公司运营的 公交线路。" href="/g21" title="兰州公交集团第一客运公司">兰州公交集团第一客运公司</a></li>,
        """
        bus_companies = lis[2].text
        bus_company_list.append(bus_companies)
        print(bus_companies)
        # 4. 最后更新时间
        last_updated = lis[3].text
        last_updated_list.append(last_updated)
        print(last_updated)
        print("-"*120)
        time.sleep(1)
        n += 1
        # 将最后的结果保存到字典中
        try:
            road_info_dic.update({"title": title_list, "run_time": run_time_list, "ticket_price": ticket_price_list,
                                  "bus_company": bus_company_list, "last_updated": last_updated_list})
            print("信息保持字典成成功~~~")
        except Exception as e:
            print("信息保持字典失败:"+e)
    print(f"获取信息成功,共获取 {n-1} 条信息")

    # print(road_info_dic)
    print("-"*120)
    info_df = pd.DataFrame(road_info_dic)
    print(f"{n1} 字头公交车所有线路信息为:")
    print(info_df)
    # 保存为csv文件(不同数字开头的公交车存为不同的文件,就是输入的数字)
    try:
        print("信息开始存入csv文件")
        progress()
        info_df.to_csv(os.path.join(os.getcwd(), 'files/') +
                       f"bus{n1}_info.csv", index=False, encoding='gbk')
        path = os.path.join(os.getcwd(), 'files')
        print("\n")
        print(f"保存csv文件成功,请在{path}文件夹下查看")
    except Exception as e:
        print("保存csv文件失败"+e)


get_every_raod_bus_info()

posted @ 2022-06-24 14:41  Aurora*  阅读(158)  评论(0编辑  收藏  举报
-->