btc1996

当我们需要从网页中获取一些需要的数据时,我们可以使用一些html网页分析的函数库来快速的获取数据。目前有多款解析HTML网页的第三方库可供使用,例如lxml,beautiful soup等等。下面以lxml为例从网页中爬取我们需要的统计数据

我希望从北京公交网站获取北京公交的所有线路信息,从而为后续处理做准备

首先引用requests用于向网页发出访问请求,获取html网页原始数据

import requests

再引用lxml中的etree类

import lxml.etree

首先输入我们起始的爬取地址,公交线路网页的索引页,以此为起点,获取所有的线路对应的url的值

lxml.etree将html网页按照标签进行一层一层的划分,形成逐渐向下生长的树结构,我们通过查看网页的源代码找到我们想要的数据在哪个标签内,使用xpath函数提取对应标签内的数据

def get_all_line():
    url = \'http://beijing.gongjiao.com/lines_all.html\'
    text = requests.get(url).text
    doc = lxml.etree.HTML(text)
    all_lines = doc.xpath("//div[@class=\'list\']/ul/li")
    f=open("./data/"+\'allline.txt\',\'a\')
    print(len(all_lines))
    for line in all_lines:
        line_name = line.xpath("./a/text()")[0].strip()
        line_url = line.xpath("./a/@href")[0]
        f.write(line_name+\'$$\'+line_url+\'\n\')
    f.close()

这样我们获得了所有线路对应的url,在此基础上再依次爬取每一个线路网页的相关数据

在爬取线路数据之前,我们需要先建立字典用于保存不同字段的数据,便于管理。根据需要,我建立了一个13个字段的字典

df_dict = {
\'line_name\': [], \'line_url\': [], \'line_start\': [], \'line_stop\': [],
\'line_op_time\': [], \'line_interval\': [], \'line_price\': [], \'line_company\': [],
\'line_up_times\': [], \'line_station_up\': [], \'line_station_up_len\': [],
\'line_station_down\': [], \'line_station_down_len\': [] 
}

 

从我们刚刚生成的url数据文件中读取所有的url,以下是对于读取线路数据的函数实现

def getbuslin(line):
    line_name = line[:line.find(\'$$\')]
    line_url = line[line.find(\'$$\')+2:]
    #print(line_url) 
    url = line_url
    text = requests.get(url).text
    #print(len(text))
    doc = lxml.etree.HTML(text)
    infos = doc.xpath("//div[@class=\'gj01_line_header clearfix\']")
    for info in infos:
        #f=open("./data/"+line_name+\'.txt\',\'a\')
        start_stop = info.xpath("./dl/dt/a/text()")
        #f.write(\'start-stop\'+start_stop+\'\n\')
        op_times = info.xpath("./dl/dd[1]/b/text()")
        #f.write(\'open time:\'+op_times+\'\n\')
        interval = info.xpath("./dl/dd[2]/text()")
        #f.write(\'interval:\'+interval+\'\n\')
        price = info.xpath("./dl/dd[3]/text()")
        #f.write(\'price:\'+price+\'\n\')
        company = info.xpath("./dl/dd[4]/text()")
        #f.write(\'company:\'+company+\'\n\')
        up_times = info.xpath("./dl/dd[5]/text()")

        all_stations_up = doc.xpath(\'//ul[@class="gj01_line_img JS-up clearfix"]\')
        for station in all_stations_up:
            station_up_name = station.xpath(\'./li/a/text()\')
            df_dict[\'line_station_up\'].append(station_up_name)
            df_dict[\'line_station_up_len\'].append(len(station_up_name))
            #f.write(station_name+\'\n\')
        
        all_stations_down = doc.xpath(\'//ul[@class="gj01_line_img JS-down clearfix"]\')
        if len(all_stations_down)== 0:
            #print(line_name)
            df_dict[\'line_station_down\'].append(\'\')
            df_dict[\'line_station_down_len\'].append(0)

        for station in all_stations_down: 
            station_down_name=station.xpath(\'./li/a/text()\')
            df_dict[\'line_station_down\'].append(station_down_name)
            df_dict[\'line_station_down_len\'].append(len(station_down_name))
            #f.write(station_name+\'\n\')
        #f.close()
        df_dict[\'line_name\'].append(line_name)
        df_dict[\'line_url\'].append(line_url)
        df_dict[\'line_start\'].append(start_stop[0])
        df_dict[\'line_stop\'].append(start_stop[1])
        if len(op_times)==0:
            op_times.append(defaultoptime)
        df_dict[\'line_op_time\'].append(op_times[0])
        df_dict[\'line_interval\'].append(interval[0][5:])
        df_dict[\'line_company\'].append(company[0][5:])
        df_dict[\'line_price\'].append(price[0][5:])
        df_dict[\'line_up_times\'].append(up_times[0][5:])

字典的实质依然是列表,因此对字典的操作方法可以参考列表

我从网页中提取了公交线路的线路名称,起始站,终点站,运营时间,发车间隔,票价,起始终点站,上下行所有站点

将数据全部存入建立的字典之后,保存为csv文件,这里需要用到pandas库

import pandas as pd

df = pd.DataFrame(df_dict)
df.to_csv(name+\'.csv\', encoding=\'utf-8\', index=None)

这时,我们已经把网页数据经过解析保存到了本地,以便后续的处理

由于公交车的线路数据相对静态,因此不需要进行实时更新,数据量也相对较小,但是整个程序运行下来依然需要好几分钟

这里我还没有采用多进程处理,后续可以通过多进程优化来充分利用计算机的性能缩短所需的时间

 

分类:

技术点:

相关文章:

  • 2021-12-26
  • 2021-11-01
  • 2021-12-12
  • 2022-12-23
  • 2021-12-29
  • 2021-09-09
  • 2021-11-16
猜你喜欢
  • 2021-01-20
  • 2021-06-11
  • 2022-02-25
  • 2022-12-23
  • 2021-12-26
相关资源
相似解决方案