首页 > 数据库 >【爬虫】项目篇-爬取福州公交线路并保存至MongoDB

【爬虫】项目篇-爬取福州公交线路并保存至MongoDB

时间:2024-04-05 22:55:29浏览次数:17  
标签:xpath MongoDB route stop 爬虫 爬取 text bus data

#http://www.fz-bus.cn/index.asp
#1)在MongoDB中创建一个数据库和一个集合。
#2)在程序执行过程中可输入线路名称查询公交线路,
# 每查询到一条线路的信息后,查询MongoDB数据库中是否存在该线路。若存在,则不做任何操作,否则执行第3步。
#将线路名称、起点和终点、途径站点、
# 冬季首末班车时间、非空调车价格和空调车价格以六个键值对保存为步骤1)中集合的一个文档。

import requests
import cchardet
from lxml import etree,html
from fake_useragent import UserAgent
import pymongo


def parse_url():
    items=source.xpath('//table[@width="520"][1]/tr[@bgcolor="#ECF4F9"]')

    for item in items:
        # 路线名称
        route_name=item.xpath('td[1]/div/text()')
        print(route_name)

        #起止站点
        origin_site=item.xpath('td[2]/div/text()')
        origin_site=[i.replace('\r\n',"").replace("\t","") for i in origin_site]
        print(origin_site)

        #途经站点
        passing_site=source.xpath('//table[@width="520"][2]/tr[@bgcolor="#ECF4F9"]/td[2]/div/text()')
        temp=source.xpath('//table[@width="520"][3]/tr[@bgcolor="#ECF4F9"]/td[2]/div/text()')
        passing_site=['->'.join(passing_site).replace("\r\n","")]
        passing_site.extend(['->'.join(temp).replace("\r\n","")])
        print(passing_site)

        #冬季首末班车时间
        winter_time=item.xpath('td[3]/div/text()')
        winter_time=[i for i in winter_time if '冬季' in i]
        print(winter_time)

        #非空调车价格
        non_air_price=item.xpath('td[4]/div/text()')
        print(non_air_price)

        #空调车价格
        air_price=item.xpath('td[5]/div/text()')
        print(air_price)
        data={
            '路线名称':route_name[0],
            '起止站点':'\n'.join(origin_site),
            '途经站点':'\n'.join(passing_site),
            '冬季首末班车时间':'\n'.join(winter_time),
            '非空调车价格':non_air_price[0],
            '空调车价格':air_price[0]
        }
        print(data)
        save_to_mongoDB(data)

def save_to_mongoDB(data):
    #myclient = pymongo.MongoClient("mongodb+srv://user_maria:[email protected]/myFirstDatabase?retryWrites=true&w=majority")
    myclient=pymongo.MongoClient(
        "mongodb+srv://HJY:[email protected]/myFirstDatabase?retryWrites=true&w=majority")    #创建数据库
    mydb=myclient['Fuzhou_db']
    #创建集合
    mycollection=mydb.Fuzhou_bus

    #查询数据是否已存在数据库中
    print(mycollection.find_one({'路线名称':str(route)}))
    if mycollection.find_one({'路线名称':route})!=None:
        pass

    else:
        # mycollection.insert(data)
        mycollection.insert_one(data)
    print(myclient.list_database_names())
if __name__ == '__main__':
    url="http://www.fz-bus.cn/line_Search.asp"
    route=7
    headers={
        'user-agent':UserAgent().random
    }
    req = requests.post(url, params={'Xianl': route, 'Ftype': 2},headers=headers)
    req.encoding = cchardet.detect(req.content)['encoding']
    source=html.fromstring(req.text)
    if "找不到你要查询的线路" in req.text :
        print("找不到你要查询的线路!")
    parse_url()


import requests
import cchardet
from lxml import html
import pymongo
head = {'user-agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36'}


def get_data(route):
    data = {'Xianl': route}  # , 'imageField3.x':27, 'imageField3.y':10,'Ftype':2  这些字段加不加都可以
    resp = requests.post('http://www.fz-bus.cn/line_Search.asp',data=data, headers=head)
    resp.encoding = cchardet.detect(resp.content)['encoding']
    if '找不到你要查询的线路' in resp.text:
        print(f'不存在{route}公交线路')
        return None
    else:
        root = html.fromstring(resp.text)
        table_list = root.xpath('//table[@width="520"]')
        route_name = table_list[0].xpath('tr[2]/td[1]/div/text()')[0]
        start_terminal_stop = table_list[0].xpath('tr[2]/td[2]/div')[0].xpath('string(.)')
        start_terminal_stop = '\n'.join(start_terminal_stop.split())
        begin_end_time = table_list[0].xpath('tr[2]/td[3]/div/text()')
        begin_end_time = begin_end_time[1] + '\n' + begin_end_time[3]
        price_non_air_conditioned_bus = table_list[0].xpath('tr[2]/td[4]/div/text()')[0]
        price_air_conditioned_bus = table_list[0].xpath('tr[2]/td[5]/div/text()')[0]
 #       print(route_name, start_terminal_stop, begin_end_time, price_non_air_conditioned_bus, price_air_conditioned_bus)
        bus_stop_routes = []
        for table in table_list[1:3]:
            bus_stop_tr_list = table.xpath('tr')
            bus_stop_list = []
            for bus_stop_tr in bus_stop_tr_list[2:]:
                bus_stop_name = bus_stop_tr.xpath('td[2]/div/text()')[0]
                bus_stop_list.append(bus_stop_name)
            bus_stop_routes.append('->'.join(bus_stop_list))

        bus_stop_route = '\n'.join(bus_stop_routes)
        return {'路线名称': route_name, '起止站点': start_terminal_stop, '途径站点': bus_stop_route, '冬季首末班车时间': begin_end_time, '非空调车价格': price_non_air_conditioned_bus,
                '空调车价格': price_air_conditioned_bus}


def save_to_mongodb(data):
    if data:
        client = pymongo.MongoClient()
        bus_route_db = client['bus_route']
        bus_route_collection = bus_route_db['bus_route_info']
        result = bus_route_collection.find_one({'路线名称': data['路线名称']})
        if result:
            print('数据库中已存在该线路')
        else:
            bus_route_collection.insert_one(data)
        client.close()


def show_routes():
    client = pymongo.MongoClient()
    bus_route_db = client['bus_route']
    bus_route_collection = bus_route_db['bus_route_info']
    result = bus_route_collection.find({})
    for route in result:
        print(route)
    client.close()


if __name__ == '__main__':
    route_name = input('请输入查询的公交车路线名称')
    save_to_mongodb(get_data(route_name))
    show_routes()


标签:xpath,MongoDB,route,stop,爬虫,爬取,text,bus,data
From: https://www.cnblogs.com/Gimm/p/18116349

相关文章

  • 【爬虫】debug篇-关于fake_useragent无法使用:Error occurred during loading data. Tr
    Erroroccurredduringloadingdata.Tryingtousecacheserverhttps://fake-useragent.herokuapp.com/browsers/0.1.11Traceback(mostrecentcalllast):File"D:\python\lib\site-packages\fake_useragent\utils.py",line154,inloadfori......
  • 【爬虫】项目篇-爬取豆瓣电影周榜
    目录使用re爬取+为请求头,保存为csv使用re爬取2+不保存使用xpath+lxml.html+lxml.etree使用re爬取+为请求头,保存为csvimportrequestsimportreimportcsvfromfake_useragentimportUserAgent#re文档:#https://docs.python.org/zh-cn/3.8/library/re.html#re.Sheader=......
  • 【爬虫】第三章-解析库的使用
    目录正则表达式XPathBeautifulSoupCSS-Selectorpyquery正则表达式XPathhttps://www.w3school.com.cn/xpath/xpath_axes.aspBeautifulSoupCSS-Selectorhttps://www.w3school.com.cn/css/css_list.asppyquery......
  • 【爬虫】项目篇-使用xpath爬取搜房网二手房信息
    #使用requests和xpath从搜房网上抓取福州地区的二手房房源信息#(要求获取所有分页上的房源,且每套房源包含标题、楼盘、#地点、经纬度、面积、房型、楼层、朝向、建筑年代、单价、总价、经纪人、联系电话等,缺数据的留空)。importrequestsfromlxmlimportetreefromfake_use......
  • 小白学python爬虫1
    """爬虫:通过编写程序来获取互联网上的资源需求:用程序模拟浏览器,输入一个网址,从该网址获取到资源或者内容"""#fromurllib.requestimporturlopen#url网址##url="http://www.baidu.com"#resp=urlopen(url)###print(resp.read().decode("utf-8"))......
  • Python爬虫之分布式爬虫
    分布式爬虫1.详情介绍        分布式爬虫是指将一个爬虫任务分解成多个子任务,在多个机器上同时执行,从而加快数据的抓取速度和提高系统的可靠性和容错性的技术。        传统的爬虫是在单台机器上运行,一次只能处理一个URL,而分布式爬虫通过将任务分解成多个子......
  • (某网站)评论爬虫+wordcloud可视化
    目录一、序二、没变化的三、没怎么变的四、全牛魔变了的五、全代码六、后记,但没完全后记七,词云图一、序打正大杯的时候,需要面向女性群体的信息收集,当时想到爬xhs相关笔记评论的数据本着面向csdn编程的心态,蒟蒻在csdn上狂搜各类“某网站爬虫”,什么“某网站 爬虫”,......
  • Python爬虫如何快速入门
    写了几篇网络爬虫的博文后,有网友留言问Python爬虫如何入门?今天就来了解一下什么是爬虫,如何快速的上手Python爬虫。一、什么是网络爬虫网络爬虫,英文名称为WebCrawler或Spider,是一种通过程序在互联网上自动获取信息的技术。它根据指定的规则,从互联网上下载网页、图片、视......
  • Linux系统下安装MongoDB的详细步骤
    一、概述MongoDB由C++语言编写,是一个介于关系型数据库和非关系型数据之间的产品,是非关系型数据库中功能最丰富,最像关系数据库的。它支持的数据结构非常松散,是类似与json的bson格式,因此可以存储比较复杂的数据类型。MongoDB最大的特点是它支持的查询语言非常强大,其语......
  • MongoDB用户权限管理,设置密码并连接
    MongoDB用户权限管理,设置密码并连接如何设置密码在服务启动状态下,在命令行中输入mongo;首先设置admin表的用户(必须,否则单独设置表用户无用),先执行useadmin,再执行db.createUser({user:'root',pwd:'123456',roles:['root']}),此时会创建一个名为root,密码为123456,角色为root的用......