思路是这样的,给一系列关键字:互联网电视;智能电视;数字;影音;家庭娱乐;节目;视听;版权;数据等。在活动行网站搜索页(http://www.huodongxing.com/search?city=%E5%85%A8%E5%9B%BD&pi=1)的文本输入框中分别输入每个关键字,在搜索结果中抓取需要的数据。

  首先通过Selenium+IE驱动得到每个关键字搜索结果的url(首页,因为以后各个页的url就是索引不一样)和总页数,保存的列表里面。然后再循环列表,用Selenium +phantomjs抓取每个关键字对应的url抓取对应的数据。

  

  

  

  具体代码如下:

  

# coding=utf-8
import os
import re
from selenium import webdriver
import selenium.webdriver.support.ui as ui
from selenium.webdriver.common.keys import Keys
import time
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support.select import Select
import IniFile
from selenium.webdriver.common.keys import Keys
import LogFile class huodongxing: def __init__(self):
#通过配置文件获取IEDriverServer.exe路径
configfile = os.path.join(os.getcwd(),'MeetingConfig.conf')
self.cf = IniFile.ConfigFile(configfile)
IEDriverServer = self.cf.GetValue("section", "IEDriverServer")
#每抓取一页数据延迟的时间,单位为秒,默认为5秒
self.pageDelay = 5
pageInteralDelay = self.cf.GetValue("section", "pageInteralDelay")
if pageInteralDelay:
self.pageDelay = int(pageInteralDelay) os.environ["webdriver.ie.driver"] = IEDriverServer
self.urldriver = webdriver.Ie(IEDriverServer)
# self.driver = webdriver.PhantomJS()
self.wait = ui.WebDriverWait(self.urldriver, 20)
self.urldriver.maximize_window() def compareDate(self,dateLeft, dateRight):
'''
比较俩个日期的大小
:param dateLeft: 日期 格式2017-03-04
:param dateRight:日期 格式2017-03-04
:return: 1:左大于右,0:相等,-1:左小于右
'''
dls = dateLeft.split('-')
drs = dateRight.split('-')
if len(dls) > len(drs):
return 1
if int(dls[0]) == int(drs[0]) and int(dls[1]) == int(drs[1]) and int(dls[2]) == int(drs[2]):
return 0 if int(dls[0]) > int(drs[0]):
return 1
elif int(dls[0]) == int(drs[0]) and int(dls[1]) > int(drs[1]):
return 1
elif int(dls[0]) == int(drs[0]) and int(dls[1]) == int(drs[1]) and int(dls[2]) > int(drs[2]):
return 1
return -1 def scroll_top(self):
'''
滚动条拉到顶部
:return:
'''
if self.urldriver.name == "chrome":
js = "var q=document.body.scrollTop=0" else:
js = "var q=document.documentElement.scrollTop=0"
return self.urldriver.execute_script(js) def scroll_foot(self):
'''
滚动条拉到底部
:return:
''' if self.urldriver.name == "chrome":
js = "var q=document.body.scrollTop=10000" else:
js = "var q=document.documentElement.scrollTop=10000"
return self.urldriver.execute_script(js) def get_UrlPageCountList(self,webSearchUrl,keywordList):
'''
根据关键字列表获取每个关键字搜索出内容url及对应的页数
:param webSearchUrl: 给定网址的搜索首页
:param keywordList: 关键字列表
:return: url及对应的页数的列表
'''
search_url_pageCount_list = []
# firstUrl = self.cf.GetValue("section", "webSearchUrl")
self.urldriver.get(webSearchUrl)
# self.urldriver.implicitly_wait(3)
time.sleep(3)
pageCountLable = self.cf.GetValue("section", "pageCountLable")
for keyword in keywordList:
if len(keyword) > 0:
js = "var obj = document.getElementById('mainSearchTextbox');obj.value='" + keyword + "';"
print '关键字:%s' % keyword
self.urldriver.execute_script(js)
# 点击搜索链接
ss_elements = self.urldriver.find_element_by_id("mainSearchTextbox")
ss_elements.send_keys(Keys.RETURN)
time.sleep(5)
current_url = self.urldriver.current_url.replace('pi=1', 'pi=')
try:
elements = self.urldriver.find_elements_by_xpath(pageCountLable)
# 要爬虫的页数
strCount = elements[0].text.encode('utf8')
pageCount = int(strCount) / 10
if int(strCount) % 10 > 0:
pageCount = pageCount + 1
search_url_pageCount_list.append(current_url + '_' + str(pageCount))
except Exception, e:
print e.message self.urldriver.close()
self.urldriver.quit()
self.driver = webdriver.PhantomJS()
self.wait = ui.WebDriverWait(self.driver, 20)
self.driver.maximize_window()
return search_url_pageCount_list def scrapy_Data(self):
'''抓取数据'''
start = time.clock() webSearchUrl = self.cf.GetValue("section", "webSearchUrl")
keyword = self.cf.GetValue("section", "keywords")
keywordList = keyword.split(';')
#搜索页及对应的页数
search_url_pageCount_list = self.get_UrlPageCountList(webSearchUrl,keywordList) if len(search_url_pageCount_list) > 0:
htmlLable = self.cf.GetValue("section", "htmlLable")
# logfile = os.path.join(os.getcwd(), r'log.txt')
# log = LogFile.LogFile(logfile) OriginalUrlLabel = self.cf.GetValue("section", "OriginalUrlLabel")
currentDate = time.strftime('%Y-%m-%d')
datePattern = re.compile(r'\d{4}-\d{2}-\d{2}')
keyword_index = 0
for url_pageCount in search_url_pageCount_list:
try:
kword = keywordList[keyword_index]
print ''
print '关键字:%s ' % kword
pageCount = int(url_pageCount.split('_')[1])
page_Count = pageCount
recordCount = 0
if pageCount > 0:
current_url = url_pageCount.split('_')[0]
pageIndex = 0
while pageCount > 0:
url = current_url + str(pageIndex)
self.driver.get(url) # 延迟3秒
time.sleep(3)
# self.driver.implicitly_wait(3)
pageCount = pageCount - 1
self.wait.until(lambda driver: self.driver.find_elements_by_xpath(htmlLable))
Elements = self.driver.find_elements_by_xpath(htmlLable) # 查找微博对应的原始url
urlList = []
self.wait.until(lambda driver: self.driver.find_elements_by_xpath(OriginalUrlLabel))
hrefElements = self.driver.find_elements_by_xpath(OriginalUrlLabel)
for hrefe in hrefElements:
urlList.append(hrefe.get_attribute('href').encode('utf8')) # self.driver.implicitly_wait(2)
index = 0
strMessage = ' '
strsplit = '\n------------------------------------------------------------------------------------\n'
index = 0
# 每页中有用记录
usefulCount = 0
for element in Elements:
txt = element.text.encode('utf8')
txts = txt.split('\n')
strDate = re.findall(datePattern, txt)
# 日期大于今天并且搜索的关键字在标题中才认为是复合要求的数据
if len(strDate) > 0 and self.compareDate(strDate[0], currentDate) == 1 and \
txts[0].find(kword) > -1:
print ' '
print txt
print '活动链接:' + urlList[index]
print strsplit strMessage = txt + "\n"
strMessage += '活动链接:' + urlList[index] + "\n"
strMessage += strsplit
strMessage = unicode(strMessage, 'utf8')
log.WriteLog(strMessage)
usefulCount = usefulCount + 1
recordCount = recordCount + 1
index = index + 1 pageIndex = pageIndex + 1
if usefulCount == 0:
break print "共浏览了: %d 页数据" % page_Count
print "共抓取了: %d 个符合条件的活动记录" % recordCount
except Exception, e:
print e.message
keyword_index = keyword_index + 1 self.driver.close()
self.driver.quit()
end = time.clock()
print "整个过程用时间: %f 秒" % (end - start) # #测试抓取数据
obj = huodongxing()
obj.scrapy_Data() 配置文件内容:
[section]
#IE驱动的路径
iedriverserver = C:\Program Files\Internet Explorer\IEDriverServer.exe pageinteraldelay = 5 #要搜索的标签,如果有多个,中间用分号隔开
htmlLable = //ul[@class='event-horizontal-list-new']/li #要获取爬虫也是的标签
pageCountLable = //span[@class='text-primary'] #给定网址的搜索首页Url
webSearchUrl = http://www.huodongxing.com/search?city=%E5%85%A8%E5%9B%BD&pi=1 #查找对应的原始url
OriginalUrlLabel = //ul[@class='event-horizontal-list-new']/li/h3/a #文本输入框要搜索的关键字
keywords = 互联网电视;智能电视;数字;影音;家庭娱乐;节目;视听;版权;数据 抓取的数据结构为:

整个过程用时间: 184.897053 秒

												

[Python爬虫] 之九:Selenium +phantomjs抓取活动行中会议活动(单线程抓取)的更多相关文章

  1. [Python爬虫] 之十一:Selenium +phantomjs抓取活动行中会议活动信息

    一.介绍 本例子用Selenium +phantomjs爬取活动行(http://www.huodongxing.com/search?qs=数字&city=全国&pi=1)的资讯信息 ...

  2. [Python爬虫] 之十:Selenium +phantomjs抓取活动行中会议活动

    一.介绍 本例子用Selenium +phantomjs爬取活动树(http://www.huodongshu.com/html/find_search.html?search_keyword=数字) ...

  3. [Python爬虫] 之一 : Selenium+Phantomjs动态获取网站数据信息

    本人刚才开始学习爬虫,从网上查询资料,写了一个利用Selenium+Phantomjs动态获取网站数据信息的例子,当然首先要安装Selenium+Phantomjs,具体的看 http://www.c ...

  4. [Python爬虫] 之八:Selenium +phantomjs抓取微博数据

    基本思路:在登录状态下,打开首页,利用高级搜索框输入需要查询的条件,点击搜索链接进行搜索.如果数据有多页,每页数据是20条件,读取页数 然后循环页数,对每页数据进行抓取数据. 在实践过程中发现一个问题 ...

  5. [Python爬虫] 之三:Selenium 调用IEDriverServer 抓取数据

    接着上一遍,在用Selenium+phantomjs 抓取数据过程中发现,有时候抓取不到,所以又测试了用Selenium+浏览器驱动的方式:具体代码如下: #coding=utf-8import os ...

  6. python爬虫动态html selenium.webdriver

    python爬虫:利用selenium.webdriver获取渲染之后的页面代码! 1 首先要下载浏览器驱动: 常用的是chromedriver 和phantomjs chromedirver下载地址 ...

  7. Python爬虫之设置selenium webdriver等待

    Python爬虫之设置selenium webdriver等待 ajax技术出现使异步加载方式呈现数据的网站越来越多,当浏览器在加载页面时,页面上的元素可能并不是同时被加载完成,这给定位元素的定位增加 ...

  8. python爬虫10 | 网站维护人员:真的求求你们了,不要再来爬取了!!

    今天 小帅b想给大家讲一个小明的小故事 ... 话说 在很久很久以前 小明不小心发现了一个叫做 学习python的正确姿势 的公众号 从此一发不可收拾 看到什么网站都想爬取 有一天 小明发现了一个小黄 ...

  9. python爬虫之初始Selenium

    1.初始 Selenium[1]  是一个用于Web应用程序测试的工具.Selenium测试直接运行在浏览器中,就像真正的用户在操作一样.支持的浏览器包括IE(7, 8, 9, 10, 11),Moz ...

随机推荐

  1. Restore IP Addresses——边界条件判定

    Given a string containing only digits, restore it by returning all possible valid IP address combina ...

  2. vue模糊搜索&select取值

    之前vue1.0的过滤器真的很好使,但是作者为了不让搬运工变得太菜.硬是砍去了过滤器,为此,我还哭了好一阵,终于,一点一点的弄明白了过滤器是怎么回事后,也学明白了vue里的属性监听器computed以 ...

  3. gulp-基本功能总汇

    研究了三天的gulp,今天做一个结束吧. 本次包含的功能有: html压缩 图片压缩 css压缩 js检测 js压缩 文件合并 文件更名 提示信息 编译less 创建服务器-浏览器实时刷新 因为我安装 ...

  4. SpringMVC调用过程

    SpringMVC中的四大组件: 1.前端控制器(DispatcherServlet)      =>[无需程序员开发] 主要是负责request和response对象的转发和响应. 2.处理器 ...

  5. shopnc 店铺二级分类添加商品

    $class_2 = $goods_class[$gc_id]['gc_parent_id']; $class_1 = $goods_class[$class_2]['gc_parent_id']; ...

  6. 最短路径-迪杰斯特拉(dijkstra)算法及优化详解

    简介: dijkstra算法解决图论中源点到任意一点的最短路径. 算法思想: 算法特点: dijkstra算法解决赋权有向图或者无向图的单源最短路径问题,算法最终得到一个最短路径树.该算法常用于路由算 ...

  7. PTA L2-004 这是二叉搜索树吗?-判断是否是对一棵二叉搜索树或其镜像进行前序遍历的结果 团体程序设计天梯赛-练习集

    L2-004 这是二叉搜索树吗? (25 分)   一棵二叉搜索树可被递归地定义为具有下列性质的二叉树:对于任一结点, 其左子树中所有结点的键值小于该结点的键值: 其右子树中所有结点的键值大于等于该结 ...

  8. EOJ Monthly 2018.8 D. Delivery Service-树上差分(边权/边覆盖)(边权转点权)(模板题)

    D. Delivery Service 单测试点时限: 2.5 秒 内存限制: 512 MB EOJ Delivery Service Company handles a massive amount ...

  9. 在浏览器中输入url地址 -> 显示主页的过程

    -来自<图解HTTP> 最近在进行前端面试方面的一些准备,看了网上许多相关的文章,发现有一个问题始终绕不开: 在浏览器中输入URL到整个页面显示在用户面前时这个过程中到底发生了什么.仔细思 ...

  10. Nginx开启跨域访问

    CORS on Nginx The following Nginx configuration enables CORS, with support for preflight requests. # ...