抓取每路公交的具体信息


目录
  • 1.抓取查询路径:
  • 2.拼接每路公交的线路链接:
  • 3.抓取每路公交的具体信息
  • 4. 实现代码

1.抓取查询路径:

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

1 2 3 4 5 6 7 8 9

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

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

https://lanzhou.8684.cn/listX

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

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

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


这里所看到的 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')
        """
        [兰州1路公交车路线, 公交公司:, 最后更新:2022-06-24]
        """
        # 标题:兰州1路公交车路线
        title = spans[0].text
        # 获取所有a标签
        a = info.select('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)
        """
        [
  • 运行时间:兰州西站5:55-00:00|兰州车站5:40-00:00
  • ,
  • 参考票价:无人售票车,1.0元一票制,支持交联IC卡/云闪付/微信/支付宝/万支付/ 翼支付/美团支付等多种支付方式
  • ,
  • 公交公司:兰州公交集团第一客运公司
  • ,
  • 最后更新:2022-06-24
    免费发送线路信息到微信
  • ,
  • ※ 本查询结果仅供参考,车程及票价请以实际发生为准
  • ] """ # 从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. 公交公司 """
  • 公交公司:兰州公交集团第一客运公司
  • , """ 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()