[Python爬虫] 之十六:Selenium +phantomjs 利用 pyquery抓取一点咨询数据
本篇主要是利用 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抓取一点咨询数据的更多相关文章
- [Python爬虫] 之三十:Selenium +phantomjs 利用 pyquery抓取栏目
一.介绍 本例子用Selenium +phantomjs爬取栏目(http://tv.cctv.com/lm/)的信息 二.网站信息 三.数据抓取 首先抓取所有要抓取网页链接,共39页,保存到数据库里 ...
- [Python爬虫] 之十七:Selenium +phantomjs 利用 pyquery抓取梅花网数据
一.介绍 本例子用Selenium +phantomjs爬取梅花网(http://www.meihua.info/a/list/today)的资讯信息,输入给定关键字抓取资讯信息. 给定关键字:数字: ...
- [Python爬虫] 之三十一:Selenium +phantomjs 利用 pyquery抓取消费主张信息
一.介绍 本例子用Selenium +phantomjs爬取央视栏目(http://search.cctv.com/search.php?qtext=消费主张&type=video)的信息(标 ...
- [Python爬虫] 之二十二:Selenium +phantomjs 利用 pyquery抓取界面网站数据
一.介绍 本例子用Selenium +phantomjs爬取界面(https://a.jiemian.com/index.php?m=search&a=index&type=news& ...
- [Python爬虫] 之二十三:Selenium +phantomjs 利用 pyquery抓取智能电视网数据
一.介绍 本例子用Selenium +phantomjs爬取智能电视网(http://news.znds.com/article/news/)的资讯信息,输入给定关键字抓取资讯信息. 给定关键字:数字 ...
- [Python爬虫] 之二十八:Selenium +phantomjs 利用 pyquery抓取网站排名信息
一.介绍 本例子用Selenium +phantomjs爬取中文网站总排名(http://top.chinaz.com/all/index.html,http://top.chinaz.com/han ...
- [Python爬虫] 之二十六:Selenium +phantomjs 利用 pyquery抓取智能电视网站图片信息
一.介绍 本例子用Selenium +phantomjs爬取智能电视网站(http://www.tvhome.com/news/)的资讯信息,输入给定关键字抓取图片信息. 给定关键字:数字:融合:电视 ...
- [Python爬虫] 之二十五:Selenium +phantomjs 利用 pyquery抓取今日头条网数据
一.介绍 本例子用Selenium +phantomjs爬取今日头条(http://www.toutiao.com/search/?keyword=电视)的资讯信息,输入给定关键字抓取资讯信息. 给定 ...
- [Python爬虫] 之二十九:Selenium +phantomjs 利用 pyquery抓取节目信息信息
一.介绍 本例子用Selenium +phantomjs爬取节目(http://tv.cctv.com/epg/index.shtml?date=2018-03-25)的信息 二.网站信息 三.数据抓 ...
随机推荐
- PHP PDO类
<?php //数据库连接类,不建议直接使用DB,而是对DB封装一层 //这个类不会被污染,不会被直接调用 class DB { //pdo对象 private $_pdo = null; // ...
- hdu5735
很美妙的一题 官方题解 http://www.cnblogs.com/duoxiao/p/5777632.html 感觉有meet in middle的思想 #include<bits/stdc ...
- (编译)使用 AppCenter 持续输出导出到 Application Insights
原文地址:https://blog.xamarin.com/appcenter-continuous-export-application-insights/ 五星手机应用有一个特殊的特点:他们不会放 ...
- 前端读者 | 关于存储及CSS的一些技巧
@羯瑞 HTML5存储 cookies 大小限制4K 发送在http请求头中 子域名能读取主域名的cookies 本地存储 localStorage sessionStorage 大小限制5M(注意超 ...
- echarts官网上的动态加载数据bug被我解决。咳咳/。
又是昨天,为什么昨天发生了这么多事.没办法,谁让我今天没事可做呢. 昨天需求是动态加载数据,画一个实时监控的折线图.大概长这样. 我屁颠屁颠的把代码copy过来,一运行,caocaocao~bug出现 ...
- oracle 优化方案小记
1. 目前状况 1.1 表空间未合理规划,导致所有的用户下的所有表都创建在默认的表空间下 oracle 使用过程中未针对特定数据表进行特定的表空间规划,导致目前实例中所有的数据库表都存储中默认的表空间 ...
- thinkphp下实现ajax无刷新分页
1.前言 作为一名php程序员,我们开发网站主要就是为了客户从客户端进行体验,在这里,thinkphp框架自带的分页类是每次翻页都要刷新一下整个页面,这种翻页的用户体验显然是不太理想的,我们希望每次翻 ...
- CodeForces 738D Sea Battle
抽屉原理. 先统计最多有$sum$个船可以放,假设打了$sum-a$枪都没打中$a$个船中的任意一个,那么再打$1$枪必中. #pragma comment(linker, "/STACK: ...
- Spring源码分析之Bean的加载流程
spring版本为4.3.6.RELEASE 不管是xml方式配置bean还是基于注解的形式,最终都会调用AbstractApplicationContext的refresh方法: @Override ...
- 解决vscode按下ctrl+S的时候自动格式化
按下ctrl+S的时候自动格式化 为什么需要这种操作? 优点: 保存的时候格式化,让我们的代码自动格式化,减少人工调整. 缺点: 有一些打好包的JS有时候修改一下,但不需要格式化,因为打好包就是要压缩 ...