Python Selenium爬取百度百科旅游景点的消息盒

一、编程环境

操作系统:Win 10
编程语言:Python 3.6

二、什么是消息盒

Infobox(消息盒)是一种模板,包含了一系列的信息框,通常是由
成对的label(标签)和data(数据)组成。
下图是百度百科词条“北京故宫”的消息盒:

1.png

三、景点名单准备

在与python文件同级的目录下创建scenic_spots_5A_namelist.txt,内容为

北京故宫
颐和园
天坛公园

2.png

四、程序

import os
import time
import codecs
from selenium import webdriver
from selenium.webdriver.common.keys import Keys


global info  # 全局变量
driver = webdriver.Chrome(executable_path="C:\Program Files (x86)\Google\Chrome\Application\chromedriver.exe")


def getInfo(name):
    try:
        # 创建路径和文件
        global info
        basePath = "scenic_spots_5A"  
        if not os.path.exists(basePath):  
            os.makedirs(basePath)  
        scenicFile = os.path.join(basePath,"scenic_info.txt")  
        if not os.path.exists(scenicFile):  
            info = codecs.open(scenicFile,'w','utf-8')  
        else:  
            info = codecs.open(scenicFile,'a','utf-8')

        driver.get("http://baike.baidu.com/")
        elem_input = driver.find_element_by_xpath("//form[@id='searchForm']/input")
        name = name.rstrip('\n')        # 景点名称是从文件中读取的,含有换行符(最后一行的景点名称可能不含护身符)
        elem_input.send_keys(name)
        elem_input.send_keys(Keys.RETURN)
        info.write(name + '\r\n')       # codecs不支持'\n'换行
        time.sleep(2)
        print (driver.current_url)
        print (driver.title)

        elem_name = driver.find_elements_by_xpath("//div[@class='basic-info cmn-clearfix']/dl/dt")    
        elem_value = driver.find_elements_by_xpath("//div[@class='basic-info cmn-clearfix']/dl/dd")  

        #create dictionary key-value  
        #字典是一种散列表结构,数据输入后按特征被散列,不记录原来的数据,顺序建议元组  
        elem_dic = dict(zip(elem_name,elem_value))   
        for key in elem_dic:    
            print (key.text,elem_dic[key].text)    
            info.writelines(key.text+" "+elem_dic[key].text+'\r\n')    
        time.sleep(5)       # 让程序停5秒,以便把信息写入文件
    except Exception as e:  
        print ("Error: ", e)
    finally:
        print('\n')
        info.write('\r\n')  # 每篇信息之后,多一行空行


def main():
    global info
    source = open("scenic_spots_5A_namelist.txt", 'r')
    for name in source:
        getInfo(name)
    print ('End Read Files!')
    time.sleep(5)
    source.close()
    info.close()
    driver.close()


main()

五、运行结果

生成了文件夹scenic_spots_5A,此文件夹中包含一个名为scenic_info.txt的文件

3.png

![4.png](https://upload-images.jianshu.io/upload_images/6946981-2da7da6e5e885cfd.png? imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

scenice_info.txt中的内容为

5.png

六、参考

https://blog.csdn.net/eastmount/article/details/48234733


TopCoder & Codeforces & AtCoder交流QQ群:648202993
更多内容请关注微信公众号
wechat_public_header.jpg

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值