前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python Selenium爬取百度百科旅游景点的基本信息

Python Selenium爬取百度百科旅游景点的基本信息

作者头像
海天一树
发布2018-07-25 14:21:36
6480
发布2018-07-25 14:21:36
举报
文章被收录于专栏:海天一树海天一树

一、编程环境

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

二、景点名单准备

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

代码语言:javascript
复制
北京故宫
颐和园
天坛公园

三、程序

代码语言:javascript
复制
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的文件

scenice_info.txt中的内容为

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2018-05-25,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 海天一树 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 一、编程环境
  • 二、景点名单准备
  • 三、程序
  • 四、运行结果
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档