[Python爬虫] Selenium获取百度百科旅游景点的InfoBox消息盒
前面我讲述过如何通过BeautifulSoup获取维基百科的消息盒,同样可以通过Spider获取网站内容,最近学习了Selenium+Phantomjs后,准备利用它们获取百度百科的旅游景点消息盒(InfoBox),这也是毕业设计实体对齐和属性的对齐的语料库前期准备工作。希望文章对你有所帮助~
源代码
# coding=utf-8
"""
Created on 2015-09-04 @author: Eastmount
""" import time
import re
import os
import sys
import codecs
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import selenium.webdriver.support.ui as ui
from selenium.webdriver.common.action_chains import ActionChains #Open PhantomJS
driver = webdriver.PhantomJS(executable_path="G:\phantomjs-1.9.1-windows\phantomjs.exe")
#driver = webdriver.Firefox()
wait = ui.WebDriverWait(driver,10)
global info #全局变量#Get the infobox of 5A tourist spots
def getInfobox(name): try: #create paths and txt filesglobal infobasePathDirectory = "Tourist_spots_5A" if not os.path.exists(basePathDirectory): os.makedirs(basePathDirectory) baiduFile = os.path.join(basePathDirectory,"BaiduSpider.txt") if not os.path.exists(baiduFile): info = codecs.open(baiduFile,'w','utf-8') else: info = codecs.open(baiduFile,'a','utf-8') #locate input notice: 1.visit url by unicode 2.write files print name.rstrip('\n') #delete char '\n' driver.get("http://baike.baidu.com/") elem_inp = driver.find_element_by_xpath("//form[@id='searchForm']/input") elem_inp.send_keys(name) elem_inp.send_keys(Keys.RETURN) info.write(name.rstrip('\n')+'\r\n') #codecs不支持'\n'换行time.sleep(2)print driver.current_urlprint driver.title#load infobox basic-info cmn-clearfixelem_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")for e in elem_name:print e.textfor e in elem_value:print e.text#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) except Exception,e: #'utf8' codec can't decode byte print "Error: ",e finally: print '\n' info.write('\r\n') #Main function
def main():global info#By function get information source = open("Tourist_spots_5A_BD.txt",'r') for name in source: name = unicode(name,"utf-8") if u'故宫' in name: #else add a '?' name = u'北京故宫' getInfobox(name) print 'End Read Files!' source.close() info.close() driver.close() main()
运行结果
主要通过从F盘中txt文件中读取国家5A级景区的名字,再调用Phantomjs.exe浏览器依次访问获取InfoBox值。同时如果存在编码问题“'ascii' codec can't encode characters”则可通过下面代码设置编译器utf-8编码,代码如下:
#设置编码utf-8
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
#显示当前默认编码方式
print sys.getdefaultencoding()
其中对应的百度百科InfoBox源代码如下图,代码中基础知识可以参考我前面的博文或我的Python爬虫专利,Selenium不仅仅擅长做自动测试,同样适合做简单的爬虫。
编码问题
此时你仍然可能遇到“'ascii' codec can't encode characters”编码问题。
它是因为你创建txt文件时默认是ascii格式,此时你的文字确实'utf-8'格式,所以需要转换通过如下方法。
import codecs#用codecs提供的open方法来指定打开的文件的语言编码,它会在读取的时候自动转换为内部unicode
if not os.path.exists(baiduFile): info = codecs.open(baiduFile,'w','utf-8')
else: info = codecs.open(baiduFile,'a','utf-8')#该方法不是io故换行是'\r\n'
info.writelines(key.text+":"+elem_dic[key].text+'\r\n')
总结
你可以代码中学习基本的自动化爬虫方法、同时可以学会如何通过for循环显示key-value键值对,对应的就是显示的属性和属性值,通过如下代码实现:
elem_dic = dict(zip(elem_name,elem_value))
但最后的输出结果不是infobox中的顺序,why?
最后希望文章对你有所帮助,还有一篇基础介绍文章,但是发表时总会引发CSDN敏感系统自动锁定,而且不知道哪里引起的触发。推荐你可以阅读~
[python爬虫] Selenium常见元素定位方法和操作的学习介绍
(By:Eastmount 2015-9-6 深夜2点半 http://blog.csdn.net/eastmount/ )
[Python爬虫] Selenium获取百度百科旅游景点的InfoBox消息盒相关推荐
- python 爬取百度知道,Python 爬虫爬取百度百科网站
利用python写一个爬虫,爬取百度百科的某一个词条下面的全部链接和每一个链接内部的词条主题和摘要.利用request库爬取页面,然后利用BeautifulSoup对爬取到的页面提取url和关键内容. ...
- 使用python爬虫爬取秒懂百科的视频
仅供学习交流使用,如有侵权,联系删除. python 爬虫抓取百度百科视频源代码 from urllib.parse import quote from bs4 import BeautifulSou ...
- [Python爬虫] Selenium+Phantomjs动态获取CSDN下载资源信息和评论
前面几篇文章介绍了Selenium.PhantomJS的基础知识及安装过程,这篇文章是一篇应用.通过Selenium调用Phantomjs获取CSDN下载资源的信息,最重要的是动态获取资源的评论,它是 ...
- python 百度百科 爬虫_爬虫爬取百度百科数据
以前段时间<青春有你2>为例,我们使用Python来爬取百度百科中<青春有你2>所有参赛选手的信息. 什么是爬虫? 为了获取大量的互联网数据,我们自然想到使用爬虫代替我们完成这 ...
- [python爬虫] Selenium常见元素定位方法和操作的学习介绍(转载)
转载地址:[python爬虫] Selenium常见元素定位方法和操作的学习介绍 一. 定位元素方法 官网地址:http://selenium-python.readthedocs.org/locat ...
- Python爬虫-Selenium(1)
Python爬虫-Selenium(1) @(博客)[python, 爬虫, selenium, Python] Python爬虫-Selenium(1) 前言 前期准备 基础使用 进阶使用 浏览器操 ...
- Python爬虫 - Selenium(4)配置启动项参数
前言:本章将详细介绍Selenium启动项参数的配置,其中包括无界面模式(在服务器上运行不设置此项会报错).浏览器窗口大小设置.浏览器User-Agent (请求头)等等. 目录 一.常用参数 二.代 ...
- python爬虫代码实例-Python爬虫爬取百度搜索内容代码实例
这篇文章主要介绍了Python爬虫爬取百度搜索内容代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 搜索引擎用的很频繁,现在利用Python爬 ...
- [Python爬虫] Selenium实现自动登录163邮箱和Locating Elements介绍
前三篇文章介绍了安装过程和通过Selenium实现访问Firefox浏览器并自动搜索"Eastmount"关键字及截图的功能.而这篇文章主要简单介绍如何实现自动登录163邮箱,同时 ...
最新文章
- tf.reduce_sum()_tf.reduce_mean()_tf.reduce_max()
- 预备作业02 20162320刘先润
- HDU 4502 吉哥系列故事——临时工计划(动态规划)
- 原型设计20条军规(转)
- 解决代码中重复的捕获 promise 错误的 try catch 语句
- [原创]linux简单之美(二)
- REVERSE-COMPETITION-GeekChallenge2021
- MyEclipse安装EGit插件方法
- linux 重启oracle_学习Linux前需要知道的事
- 推荐10个优秀GitHub仓库
- ios键盘横屏_平板电脑就只能追剧玩游戏?看这款外设键盘如何让iPad爱上办公...
- 在html标签中写css样式,html style样式标签元素教程
- 测度论与概率论基础学习笔记6——2.4可测函数的收敛性
- 贪心科技NLP训练营成果展示(附视频回放)
- 生活是苦难的,我又划着我的断桨出发了
- 宝宝湿疹怎么办?宝宝湿疹怎么处理最好?
- 计算机如何设置光驱启动,怎样将电脑设置成从光驱启动
- PS制作两寸照片的疑惑
- 无限流量与5G要来,我们距淘汰Wi-Fi还有多远?
- python实用案例合集
热门文章
- THUPCCTSAPIO摸鱼被$\Huge{\color{black}{\mathbf{z}}\color{red}{\mathbf{zh}}}$爆踩记
- Linux C编程之四 动态库(共享库)的制作
- 浏览器登陆时纪录自动登陆时限
- Golang——垃圾回收GC
- winfrom水晶报表的创建
- c语言中mw shl code,cacoshl - [ C语言中文开发手册 ] - 在线原生手册 - php中文网
- 广东金融学院计算机期末考试,关于2018-2019学年第二学期录入期末成绩的通知
- ios c语言编译环境搭建,iOS开发之runtime(一):runtime调试环境搭建
- Java黑皮书课后题第4章:*4.23(金融应用:酬金)编写一个程序,读取下面信息,然后输出一个酬金声明
- 2012 人民搜索 实习生招聘 笔试题