前面我讲述过如何通过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 files
global info
basePathDirectory = "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'换行
#print driver.current_url
time.sleep(5) #load infobox
elem_name = driver.find_elements_by_xpath("//div[@class='basic-info']/dl/dt")
elem_value = driver.find_elements_by_xpath("//div[@class='basic-info']/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) 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消息盒的更多相关文章

  1. python爬虫—爬取百度百科数据

    爬虫框架:开发平台 centos6.7 根据慕课网爬虫教程编写代码 片区百度百科url,标题,内容 分为4个模块:html_downloader.py 下载器 html_outputer.py 爬取数 ...

  2. Python 爬虫实例(爬百度百科词条)

    爬虫是一个自动提取网页的程序,它为搜索引擎从万维网上下载网页,是搜索引擎的重要组成.爬虫从一个或若干初始网页的URL开始,获得初始网页上的URL,在抓取网页的过程中,不断从当前页面上抽取新的URL放入 ...

  3. [Python爬虫] Selenium+Phantomjs动态获取CSDN下载资源信息和评论

    前面几篇文章介绍了Selenium.PhantomJS的基础知识及安装过程,这篇文章是一篇应用.通过Selenium调用Phantomjs获取CSDN下载资源的信息,最重要的是动态获取资源的评论,它是 ...

  4. python爬虫---selenium库的用法

    python爬虫---selenium库的用法 selenium是一个自动化测试工具,支持Firefox,Chrome等众多浏览器 在爬虫中的应用主要是用来解决JS渲染的问题. 1.使用前需要安装这个 ...

  5. [python爬虫] Selenium常见元素定位方法和操作的学习介绍

    这篇文章主要Selenium+Python自动测试或爬虫中的常见定位方法.鼠标操作.键盘操作介绍,希望该篇基础性文章对你有所帮助,如果有错误或不足之处,请海涵~同时CSDN总是屏蔽这篇文章,再加上最近 ...

  6. [python爬虫] Selenium常见元素定位方法和操作的学习介绍(转载)

    转载地址:[python爬虫] Selenium常见元素定位方法和操作的学习介绍 一. 定位元素方法 官网地址:http://selenium-python.readthedocs.org/locat ...

  7. [Python爬虫] Selenium实现自动登录163邮箱和Locating Elements介绍

    前三篇文章介绍了安装过程和通过Selenium实现访问Firefox浏览器并自动搜索"Eastmount"关键字及截图的功能.而这篇文章主要简单介绍如何实现自动登录163邮箱,同时 ...

  8. [Python爬虫] Selenium爬取新浪微博客户端用户信息、热点话题及评论 (上)

    转载自:http://blog.csdn.net/eastmount/article/details/51231852 一. 文章介绍 源码下载地址:http://download.csdn.net/ ...

  9. Python爬虫 - 爬取百度html代码前200行

    Python爬虫 - 爬取百度html代码前200行 - 改进版,  增加了对字符串的.strip()处理 源代码如下: # 改进版, 增加了 .strip()方法的使用 # coding=utf-8 ...

随机推荐

  1. Java课程实验报告 实验一 Java开发环境的熟悉

    北京电子科技学院(BESTI) 实     验    报     告 课程:Java程序设计 班级:1353 姓名:韩玉琪 学号:20135317 成绩:            指导教师:娄嘉鹏  实 ...

  2. sql left join、right join、inner join

    left join(左联接) 返回包括左表中的所有记录和右表中联结字段相等的记录 right join(右联接) 返回包括右表中的所有记录和左表中联结字段相等的记录inner join(等值连接) 只 ...

  3. 【BZOJ2756】奇怪的游戏(二分,最小割)

    题意: Blinker最近喜欢上一个奇怪的游戏.这个游戏在一个 N*M 的棋盘上玩,每个格子有一个数.每次 Blinker 会选择两个相邻的格子,并使这两个数都加上 1.现在 Blinker 想知道最 ...

  4. 一个简单的SNTP客户端

    借鉴于python网络编程攻略 #/usr/local/bin/python3.5 #coding:utf-8 import socket, struct, time NTP_server = &qu ...

  5. ASP.NET ZERO 学习 事件总线

    用于注册和触发客户端的全局事件. 介绍 Pub/sub事件模型广泛用于客户端,ABP包含了一个简单的全局事件总线来 注册并 触发事件. 注册事件 可以使用abp.event.on来注册一个全局事件.一 ...

  6. [题解]某模拟题(USACO月赛部分题+noip2005部分题)

    题目描述 农场上有N(1 <= N <= 50,000)堆草,放在不同的地点上.FJ有一辆拖拉机,也在农场上.拖拉机和草堆都表示为二维平面上的整数坐标,坐标值在1..1000的范围内.拖拉 ...

  7. python学习之——计算给出代码中注释、代码、空行的行数

    题目:计算给出代码中注释.代码.空行的行数 来源:网络 思路:注释行以 ‘#’开头,空行以 ‘\n’ 开头,以此作为判断 def count_linenum(fname): fobj = open(f ...

  8. RHEL 集群(RHCS)配置小记 -- 文档记录

    1.RHEL 6 集群配置官方管理手册 https://access.redhat.com/site/documentation/zh-CN/Red_Hat_Enterprise_Linux/6/pd ...

  9. 在windows环境下基于sublime text3的node.js开发环境搭建

    首先安装sublime text3,百度一堆,自己找吧.理论上sublime text2应该也可以.我只能说一句:这个软件实在是太强悍了. 跨平台,丰富的插件体系,加上插件基本上就是一个强悍的ide了 ...

  10. Android.技术站点

    总结Android相关的技术站点和blog 1. http://android-developers.blogspot.com/ 首推这个blog,有时间需要每篇blog读一遍. 2. nlopez ...