本篇主要是利用 pyquery来定位抓取数据,而不用xpath,通过和xpath比较,pyquery效率要高。

  

  主要代码:

 

# coding=utf-8
import os
import re
from selenium import webdriver
import selenium.webdriver.support.ui as ui
import time
from datetime import datetime
from selenium.webdriver.common.action_chains import ActionChains
import IniFile
from threading import Thread
from pyquery import PyQuery as pq
import LogFile
import mongoDB class yidianzixunSpider(object):
def __init__(self): logfile = os.path.join(os.path.dirname(os.getcwd()), time.strftime('%Y-%m-%d') + '.txt')
self.log = LogFile.LogFile(logfile)
configfile = os.path.join(os.path.dirname(os.getcwd()), 'setting.conf')
cf = IniFile.ConfigFile(configfile)
self.webSearchUrl_list = cf.GetValue("yidianzixun", "webSearchUrl").split(';')
self.keyword_list = cf.GetValue("section", "information_keywords").split(';')
self.db = mongoDB.mongoDbBase()
self.start_urls = []
for url in self.webSearchUrl_list:
self.start_urls.append(url) self.driver = webdriver.PhantomJS()
self.wait = ui.WebDriverWait(self.driver, 2)
self.driver.maximize_window() def scroll_foot(self):
'''
滚动条拉到底部
:return:
'''
js = ""
# 如何利用chrome驱动或phantomjs抓取
if self.driver.name == "chrome" or self.driver.name == 'phantomjs':
js = "var q=document.body.scrollTop=10000"
# 如何利用IE驱动抓取
elif self.driver.name == 'internet explorer':
js = "var q=document.documentElement.scrollTop=10000"
return self.driver.execute_script(js) def Comapre_to_days(self, leftdate, rightdate):
'''
比较连个字符串日期,左边日期大于右边日期多少天
:param leftdate: 格式:2017-04-15
:param rightdate: 格式:2017-04-15
:return: 天数
'''
l_time = time.mktime(time.strptime(leftdate, '%Y-%m-%d'))
r_time = time.mktime(time.strptime(rightdate, '%Y-%m-%d'))
result = int(l_time - r_time) / 86400
return result def date_isValid(self, strDateText):
'''
判断日期时间字符串是否合法:如果给定时间大于当前时间是合法,或者说当前时间给定的范围内
:param strDateText: 四种格式 '2小时前'; '2天前' ; '昨天' ;'2017.2.12 '
:return: True:合法;False:不合法
'''
currentDate = time.strftime('%Y-%m-%d')
if strDateText.find('分钟前') > 0 or strDateText.find('刚刚') > -1:
return True, currentDate
elif strDateText.find('小时前') > 0:
datePattern = re.compile(r'\d{1,2}')
ch = int(time.strftime('%H')) # 当前小时数
strDate = re.findall(datePattern, strDateText)
if len(strDate) == 1:
if int(strDate[0]) <= ch: # 只有小于当前小时数,才认为是今天
return True, currentDate
return False, '' def log_print(self, msg):
'''
# 日志函数
# :param msg: 日志信息
# :return:
# '''
print '%s: %s' % (time.strftime('%Y-%m-%d %H-%M-%S'), msg) def scrapy_date(self):
strsplit = '------------------------------------------------------------------------------------'
for link in self.start_urls: for i in range(5):
self.scroll_foot()
# time.sleep(1)
self.driver.get(link)
selenium_html = self.driver.execute_script("return document.documentElement.outerHTML")
doc = pq(selenium_html)
infoList = [] self.log.WriteLog(strsplit)
self.log_print(strsplit)
Elements = doc('a[class^="item doc style-"]') # class属性内容以item doc style-开始的元素
for element in Elements.items():
date = element('span[class="date"]').text().encode('utf8').strip()
flag, strDate = self.date_isValid(date)
if flag:
title = element('div[class="doc-title"]').text().encode('utf8').strip() for keyword in self.keyword_list:
if title.find(keyword) > -1:
url = 'http://www.yidianzixun.com' + element.attr('href')
source = element('span[class="source"]').text().encode('utf8').strip() dictM = {'title': title, 'date': strDate,
'url': url, 'keyword': keyword, 'introduction': title, 'source': source}
infoList.append(dictM)
self.log.WriteLog('title:%s'%title)
self.log.WriteLog('url:%s' % url)
self.log.WriteLog('source:%s' % source)
self.log.WriteLog('kword:%s' % keyword) self.log_print('title:%s' % title)
self.log_print('url:%s' % url)
self.log_print('source:%s' % source)
self.log_print('kword:%s' % keyword)
break
if len(infoList)>0:
self.db.SaveInformations(infoList)
self.driver.close()
self.driver.quit() # obj = yidianzixunSpider()
# obj.scrapy_date()

[Python爬虫] 之十六:Selenium +phantomjs 利用 pyquery抓取一点咨询数据的更多相关文章

  1. [Python爬虫] 之三十:Selenium +phantomjs 利用 pyquery抓取栏目

    一.介绍 本例子用Selenium +phantomjs爬取栏目(http://tv.cctv.com/lm/)的信息 二.网站信息 三.数据抓取 首先抓取所有要抓取网页链接,共39页,保存到数据库里 ...

  2. [Python爬虫] 之十七:Selenium +phantomjs 利用 pyquery抓取梅花网数据

    一.介绍 本例子用Selenium +phantomjs爬取梅花网(http://www.meihua.info/a/list/today)的资讯信息,输入给定关键字抓取资讯信息. 给定关键字:数字: ...

  3. [Python爬虫] 之三十一:Selenium +phantomjs 利用 pyquery抓取消费主张信息

    一.介绍 本例子用Selenium +phantomjs爬取央视栏目(http://search.cctv.com/search.php?qtext=消费主张&type=video)的信息(标 ...

  4. [Python爬虫] 之二十二:Selenium +phantomjs 利用 pyquery抓取界面网站数据

    一.介绍 本例子用Selenium +phantomjs爬取界面(https://a.jiemian.com/index.php?m=search&a=index&type=news& ...

  5. [Python爬虫] 之二十三:Selenium +phantomjs 利用 pyquery抓取智能电视网数据

    一.介绍 本例子用Selenium +phantomjs爬取智能电视网(http://news.znds.com/article/news/)的资讯信息,输入给定关键字抓取资讯信息. 给定关键字:数字 ...

  6. [Python爬虫] 之二十八:Selenium +phantomjs 利用 pyquery抓取网站排名信息

    一.介绍 本例子用Selenium +phantomjs爬取中文网站总排名(http://top.chinaz.com/all/index.html,http://top.chinaz.com/han ...

  7. [Python爬虫] 之二十六:Selenium +phantomjs 利用 pyquery抓取智能电视网站图片信息

    一.介绍 本例子用Selenium +phantomjs爬取智能电视网站(http://www.tvhome.com/news/)的资讯信息,输入给定关键字抓取图片信息. 给定关键字:数字:融合:电视 ...

  8. [Python爬虫] 之二十五:Selenium +phantomjs 利用 pyquery抓取今日头条网数据

    一.介绍 本例子用Selenium +phantomjs爬取今日头条(http://www.toutiao.com/search/?keyword=电视)的资讯信息,输入给定关键字抓取资讯信息. 给定 ...

  9. [Python爬虫] 之二十九:Selenium +phantomjs 利用 pyquery抓取节目信息信息

    一.介绍 本例子用Selenium +phantomjs爬取节目(http://tv.cctv.com/epg/index.shtml?date=2018-03-25)的信息 二.网站信息 三.数据抓 ...

随机推荐

  1. ubuntu 软件包(package)更换源(source)为阿里云镜像 update&upgrade

    在ubuntu下用apt-get install安装软件时,发现package list中没有所需的软件, 估计可能是package list太旧了,于是需要apt-get update & ...

  2. 【hdoj_2570】迷障

    题目:http://acm.hdu.edu.cn/showproblem.php?pid=2570 思路:贪心法.要求在浓度不超标的情况下,解药的最大体积.由于体积相同,可以先对浓度排序,然后从浓度小 ...

  3. 2t3ik、ddgs与Linux异常文件下载处理

    异常1: 这样的邮件发生了两周了,烦得很.进入服务器,用top看来下进程. 解决办法 首先 kill 相关PID 进入/tmp/   删除相关文件 rm -rf 2t3ik相关文件 不给相关文件修改权 ...

  4. python selenium firefox 添加cookie add_cookie

    from selenium import webdriver driver = webdriver.Firefox() driver.get('http://www.baidu.com') cooki ...

  5. 洛谷——P1123 取数游戏

    P1123 取数游戏 题目描述 一个N×M的由非负整数构成的数字矩阵,你需要在其中取出若干个数字,使得取出的任意两个数字不相邻(若一个数字在另外一个数字相邻8个格子中的一个即认为这两个数字相邻),求取 ...

  6. 洛谷——P1743 矩阵 III

    P1743 矩阵 III 题目背景 usqwedf 改编系列题. 题目描述 给定一个n*m的矩阵,问从左上角走到右下角有多少条路径. 输入输出格式 输入格式: 一行两个正整数 n,m 输出格式: 路径 ...

  7. SecureCRT、Xmanager对Linux上传下载文件或文件夹

    (1).SecureCRT SecureCRT对Linux上传下载文件或文件夹拥有一个专门的软件SecureFXPortable.对于它来说只有两个的难题,一个是版本问题,尽量去官网下载最近版本:另一 ...

  8. Server SQL 2008 练习

    一.修改数据库 (1)给db_temp数据库添加一个数据文件文件db_temp1指定大小为5MB,最大文件大小为100mb,自动递增大小为1MB,存储路径为d:\. 利用系统存储过程sp_helpdb ...

  9. Web应用主动侦测工具Skipfish

    Web应用主动侦测工具Skipfish   Skipfish是Kali Linux附带的一个主动Web应用侦测工具.该工具会首先尽可能获取所有网站路径,进行访问,然后根据返回的内容,检测是否存在漏洞. ...

  10. Codeforces 285 E. Positions in Permutations

    \(>Codeforces \space 285 E. Positions in Permutations<\) 题目大意 : 定义一个长度为 \(n\) 的排列中第 \(i\) 个元素是 ...