以下是使用Python编写的爬取株洲市公交常规线路页面的代码:

import requests
from bs4 import BeautifulSoup

# 定义爬取页面的URL
url = "https://zhuzhou.8684.cn/line1"

# 发送请求,获取页面内容
response = requests.get(url)
html = response.text

# 使用BeautifulSoup解析页面内容
 soup = BeautifulSoup(html, "html.parser")

# 获取公交线路名
bus_name = soup.select_one(".bus_i_t1").text.strip()

# 获取上行和下行站点
up_stations = soup.select(".bus_line_site .bus_line_site_name1")
down_stations = soup.select(".bus_line_site .bus_line_site_name2")

# 将站点名称拼接成字符串,并用逗号隔开
up_stations_str = ",".join([station.text.strip() for station in up_stations])
down_stations_str = ",".join([station.text.strip() for station in down_stations])

# 将数据保存到txt文件
with open("bus_stations.txt", "w", encoding="utf-8") as file:
    file.write(f"{bus_name}|{up_stations_str}|{down_stations_str}")

运行以上代码后,会在当前目录下生成一个名为bus_stations.txt的文件,其中包含了株洲市区每天公交线路经过的站点数据。每一行表示一个公交线路的数据,包括公交线路名、上行站点和下行站点,列与列之间用|隔开。


原文地址: https://www.cveoy.top/t/topic/pwA3 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录