[Python爬虫] Selenium获取百度百科旅游景点的InfoBox消息盒

前面我讲述过如何通过BeautifulSoup获取维基百科的消息盒,同样可以通过Spider获取网站内容,最近学习了Selenium+Phantomjs后,准备利用它们获取百度百科的旅游景点消息盒(InfoBox),这也是毕业设计实体对齐和属性的对齐的语料库前期准备工作。希望文章对你有所帮助~

源代码

 1 # coding=utf-8
 2 """
 3 Created on 2015-09-04 @author: Eastmount
 4 """
 5
 6 import time
 7 import re
 8 import os
 9 import sys
10 import codecs
11 from selenium import webdriver
12 from selenium.webdriver.common.keys import Keys
13 import selenium.webdriver.support.ui as ui
14 from selenium.webdriver.common.action_chains import ActionChains
15
16 #Open PhantomJS
17 driver = webdriver.PhantomJS(executable_path="G:\phantomjs-1.9.1-windows\phantomjs.exe")
18 #driver = webdriver.Firefox()
19 wait = ui.WebDriverWait(driver,10)
20 global info #全局变量
21
22 #Get the infobox of 5A tourist spots
23 def getInfobox(name):
24     try:
25         #create paths and txt files
26         global info
27         basePathDirectory = "Tourist_spots_5A"
28         if not os.path.exists(basePathDirectory):
29             os.makedirs(basePathDirectory)
30         baiduFile = os.path.join(basePathDirectory,"BaiduSpider.txt")
31         if not os.path.exists(baiduFile):
32             info = codecs.open(baiduFile,‘w‘,‘utf-8‘)
33         else:
34             info = codecs.open(baiduFile,‘a‘,‘utf-8‘)
35
36         #locate input  notice: 1.visit url by unicode 2.write files
37         print name.rstrip(‘\n‘) #delete char ‘\n‘
38         driver.get("http://baike.baidu.com/")
39         elem_inp = driver.find_element_by_xpath("//form[@id=‘searchForm‘]/input")
40         elem_inp.send_keys(name)
41         elem_inp.send_keys(Keys.RETURN)
42         info.write(name.rstrip(‘\n‘)+‘\r\n‘)  #codecs不支持‘\n‘换行
43         #print driver.current_url
44         time.sleep(5)
45
46         #load infobox
47         elem_name = driver.find_elements_by_xpath("//div[@class=‘basic-info‘]/dl/dt")
48         elem_value = driver.find_elements_by_xpath("//div[@class=‘basic-info‘]/dl/dd")
49
50         #create dictionary key-value
51         #字典是一种散列表结构,数据输入后按特征被散列,不记录原来的数据,顺序建议元组
52         elem_dic = dict(zip(elem_name,elem_value))
53         for key in elem_dic:
54             print key.text,elem_dic[key].text
55             info.writelines(key.text+" "+elem_dic[key].text+‘\r\n‘)
56         time.sleep(5)
57
58     except Exception,e: #‘utf8‘ codec can‘t decode byte
59         print "Error: ",e
60     finally:
61         print ‘\n‘
62         info.write(‘\r\n‘)
63
64 #Main function
65 def main():
66     global info
67     #By function get information
68     source = open("Tourist_spots_5A_BD.txt",‘r‘)
69     for name in source:
70         name = unicode(name,"utf-8")
71         if u‘故宫‘ in name: #else add a ‘?‘
72             name = u‘北京故宫‘
73         getInfobox(name)
74     print ‘End Read Files!‘
75     source.close()
76     info.close()
77     driver.close()
78
79 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‘格式,所以需要转换通过如下方法。

 1 import codecs
 2
 3 #用codecs提供的open方法来指定打开的文件的语言编码,它会在读取的时候自动转换为内部unicode
 4 if not os.path.exists(baiduFile):
 5     info = codecs.open(baiduFile,‘w‘,‘utf-8‘)
 6 else:
 7     info = codecs.open(baiduFile,‘a‘,‘utf-8‘)
 8
 9 #该方法不是io故换行是‘\r\n‘
10 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/

时间: 2024-08-03 11:20:51

[Python爬虫] Selenium获取百度百科旅游景点的InfoBox消息盒的相关文章

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

爬虫框架:开发平台 centos6.7 根据慕课网爬虫教程编写代码 片区百度百科url,标题,内容 分为4个模块:html_downloader.py 下载器 html_outputer.py 爬取数据生成html模块 html_parser 获取有用数据 url_manager url管理器 spider_main 爬虫启动代码 spider_main.py 1 #!/usr/bin/python 2 #-*- coding: utf8 -*- 3 4 import html_download

Python爬虫练习爬百度百科python词条

1.spider_main # coding:utf8 from baike_spider import url_manager, html_downloader, html_parser, html_outputer class SpiderMain(object): def __init__(self): self.urls = url_manager.UrlManager() self.downloader = html_downloader.HtmlDownLoader() self.p

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

这篇文章主要Selenium+Python自动测试或爬虫中的常见定位方法.鼠标操作.键盘操作介绍,希望该篇基础性文章对你有所帮助,如果有错误或不足之处,请海涵~ 前文目录: [Python爬虫] 在Windows下安装PhantomJS和CasperJS及入门介绍(上) [Python爬虫] 在Windows下安装PIP+Phantomjs+Selenium [Python爬虫] Selenium自动访问Firefox和Chrome并实现搜索截图 [Python爬虫] Selenium实现自动登

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

一. 文章介绍 前一篇文章"[python爬虫] Selenium爬取新浪微博内容及用户信息"简单讲述了如何爬取新浪微博手机端用户信息和微博信息. 用户信息:包括用户ID.用户名.微博数.粉丝数.关注数等. 微博信息:包括转发或原创.点赞数.转发数.评论数.发布时间.微博内容等. 它主要通过从文本txt中读取用户id,通过"URL+用户ID" 访问个人网站,如柳岩: http://weibo.cn/guangxianliuya 因为手机端数据相对精简简单,所以采用输

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

目录(?)[+] 前三篇文章介绍了安装过程和通过Selenium实现访问Firefox浏览器并自动搜索"Eastmount"关键字及截图的功能.而这篇文章主要简单介绍如何实现自动登录163邮箱,同时继续介绍Selenium+Python官网Locating Elements部分内容.        希望该篇基础性文章对你有所帮助,如果有错误或不足之处,请海涵~        [Python爬虫] 在Windows下安装PhantomJS和CasperJS及入门介绍(上)        

[Python爬虫] Selenium爬取新浪微博移动端热点话题及评论 (下)

这篇文章主要讲述了使用python+selenium爬取新浪微博的热点话题和评论信息.其中使用该爬虫的缺点是效率极低,傻瓜式的爬虫,不能并行执行等,但是它的优点是采用分析DOM树结构分析网页源码并进行信息爬取,同时它可以通过浏览器进行爬取中间过程的演示及验证码的输入.这篇文章对爬虫的详细过程就不再论述了,主要是提供可运行的代码和运行截图即可.希望文章对你有所帮助吧~ 参考文章 [python爬虫] Selenium爬取新浪微博内容及用户信息 [Python爬虫] Selenium爬取新浪微博客户

[python爬虫] Selenium定向爬取虎扑篮球海量精美图片

前言: 作为一名从小就看篮球的球迷,会经常逛虎扑篮球及湿乎乎等论坛,在论坛里面会存在很多精美图片,包括NBA球队.CBA明星.花边新闻.球鞋美女等等,如果一张张右键另存为的话真是手都点疼了.作为程序员还是写个程序来进行吧!        所以我通过Python+Selenium+正则表达式+urllib2进行海量图片爬取.        前面讲过太多Python爬虫相关的文章了,如爬取新浪博客.维基百科Infobox.百度百科.游迅网图片,也包括Selenium安装过程等等,详见我的两个专栏: 

[python爬虫] Selenium定向爬取海量精美图片及搜索引擎杂谈

我自认为这是自己写过博客中一篇比较优秀的文章,同时也是在深夜凌晨2点满怀着激情和愉悦之心完成的.首先通过这篇文章,你能学到以下几点:        1.可以了解Python简单爬取图片的一些思路和方法        2.学习Selenium自动.测试分析动态网页和正则表达式的区别和共同点        3.了解作者最近学习得比较多的搜索引擎和知识图谱的整体框架        4.同时作者最近找工作,里面的一些杂谈和建议也许对即将成为应届生的你有所帮助        5.当然,最重要的是你也可以尝

[Python爬虫] Selenium自动访问Firefox和Chrome并实现搜索截图

前两篇文章介绍了安装,此篇文章算是一个简单的进阶应用吧!它是在Windows下通过Selenium+Python实现自动访问Firefox和Chrome并实现搜索截图的功能.        [Python爬虫] 在Windows下安装PhantomJS和CasperJS及入门介绍(上)        [Python爬虫] 在Windows下安装PIP+Phantomjs+Selenium 自动访问Firefox 可以参照前文安装Selenium环境,目前Selenium这个用于Web应用程序测试