思路是这样的,给一系列关键字:互联网电视;智能电视;数字;影音;家庭娱乐;节目;视听;版权;数据等。在活动行网站搜索页(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. [转载] 更改pip源至国内镜像,显著提升下载速度

    原文地址: https://blog.csdn.net/lambert310/article/details/52412059 经常在使用python的时候需要安装各种模块,而pip是很强大的模块安装 ...

  2. AC日记——小A的糖果 洛谷七月月赛

    小A的糖果 思路: for循环贪心: 代码: #include <bits/stdc++.h> using namespace std; #define maxn 100005 #defi ...

  3. node-java模块

    node-java模块 node-java使得开发人员,可以调用java优秀的jar包资源.有些方法逻辑,可能node不容易实现,但是java就可以很方便去做.这个时候,就可以使用node-java这 ...

  4. onethink 重写URL后,apache提示No input file specified

    <IfModule mod_rewrite.c> RewriteEngine on RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{RE ...

  5. gcc、make、makefile、cmake、cmakelists区别

      文章来源:见下!   作者:辉常哥链接:https://www.zhihu.com/question/36609459/answer/89743845来源:知乎著作权归作者所有.商业转载请联系作者 ...

  6. Bzoj 3498 Cakes(三元环)

    题面(权限题就不放题面了) 题解 三元环模板题,按题意模拟即可. #include <cstdio> #include <cstring> #include <vecto ...

  7. 浮生半日:探究Python字节码

    好吧!“人生苦短,请用Python”,作为python爱好者以及安全从业者,而且最近也碰到了一些这方面的问题,懂点python字节码还是很有必要的. Python是一门解释性语言,它的具体工作流程如下 ...

  8. Oracle concat

    如果要进行多个字符串的拼接的话,可以使用多个CONCAT()函数嵌套使用,上面的SQL可以如下改写:SELECT CONCAT(CONCAT(CONCAT('工号为',FNumber),'的员工姓名为 ...

  9. 文本转化工具dos2unix

    文本转化工具dos2unix   由于历史原因,各个平台使用的文本编码规范不同,导致了同一文本在不同平台中显示不同.例如,Windows和Linux的换行符号不同,会造成多行文本显示混乱.为了解决这个 ...

  10. POJ 2348 Euclid's Game 博弈论

    http://poj.org/problem?id=2348 顺便说,必应翻译真的好用,比谷歌翻译好用100倍. 很难判断这道题的具体博弈类型. 有两种写法,一种是找规律,一种是推理得到关系后循环(或 ...