[Python爬虫] 之二十一:Selenium +phantomjs 利用 pyquery抓取36氪网站数据
一、介绍
本例子用Selenium +phantomjs爬取36氪网站(http://36kr.com/search/articles/电视?page=1)的资讯信息,输入给定关键字抓取资讯信息。
给定关键字:数字;融合;电视
抓取信息内如下:
1、资讯标题
2、资讯链接
3、资讯时间
4、资讯来源
二、网站信息


三、数据抓取
针对上面的网站信息,来进行抓取
1、首先抓取信息列表
抓取代码:Elements = doc('li[class="item"]')
2、抓取标题
抓取代码:title = element('div[class="intro"]').find('h3').find('div').text().encode('utf8').strip().replace(' ','')
3、抓取链接
抓取代码:url = 'http://36kr.com' + element.find('a').attr('href')
4、抓取日期
抓取代码:strdate = element('span[class="time"]').text().encode('utf8').strip()
5、抓取来源
抓取代码:source = element('div[class="am-cf inner_li"]').find('span[class="company mark h5_mark"]').text().encode('utf8').strip()
四、完整代码
# coding=utf-8
import os
import re
from selenium import webdriver
import selenium.webdriver.support.ui as ui
import time
from datetime import datetime
import IniFile
# from threading import Thread
from pyquery import PyQuery as pq
import LogFile
import mongoDB
import urllib
class kr36Spider(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)
webSearchUrl_list = cf.GetValue("kr36", "webSearchUrl")
self.keyword_list = cf.GetValue("section", "information_keywords").split(';')
self.db = mongoDB.mongoDbBase()
self.start_urls = []
for word in self.keyword_list:
self.start_urls.append(webSearchUrl_list + urllib.quote(word)) 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: 四种格式 '慧聪网 7小时前'; '新浪游戏 29分钟前' ; '中国行业研究网 2017-6-13'
:return: True:合法;False:不合法
'''
currentDate = time.strftime('%Y-%m-%d')
datePattern = re.compile(r'\d{4}-\d{1,2}-\d{1,2}')
strDate = re.findall(datePattern, strDateText)
if len(strDate) == 1:
if self.Comapre_to_days(currentDate, strDate[0])< 20:
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:
self.driver.get(link)
time.sleep(1)
self.scroll_foot()
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('li[class="item"]')
for element in Elements.items():
strdate = element('span[class="time"]').text().encode('utf8').strip()
flag, date = self.date_isValid(strdate)
if flag:
title = element('div[class="intro"]').find('h3').find('div').text().encode('utf8').strip().replace(' ','') for keyword in self.keyword_list:
if title.find(keyword) > -1:
url = 'http://36kr.com' + element.find('a').attr('href')
source = element('div[class="am-cf inner_li"]').find(
'span[class="company mark h5_mark"]').text().encode('utf8').strip() dictM = {'title': title, 'date': date,
'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.WriteLog(strsplit) self.log_print('title:%s' % dictM['title'])
self.log_print('url:%s' % dictM['url'])
self.log_print('date:%s' % dictM['date'])
self.log_print('source:%s' % dictM['source'])
self.log_print('kword:%s' % dictM['keyword'])
self.log_print(strsplit)
break
if len(infoList)>0:
self.db.SaveInformations(infoList) self.driver.close()
self.driver.quit() obj = kr36Spider()
obj.scrapy_date()
[Python爬虫] 之二十一:Selenium +phantomjs 利用 pyquery抓取36氪网站数据的更多相关文章
- [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://www.toutiao.com/search/?keyword=电视)的资讯信息,输入给定关键字抓取资讯信息. 给定 ...
- [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://www.tvhome.com/news/)的资讯信息,输入给定关键字抓取图片信息. 给定关键字:数字:融合:电视 ...
- [Python爬虫] 之二十四:Selenium +phantomjs 利用 pyquery抓取中广互联网数据
一.介绍 本例子用Selenium +phantomjs爬取中广互联网(http://www.tvoao.com/select.html)的资讯信息,输入给定关键字抓取资讯信息. 给定关键字:数字:融 ...
- [Python爬虫] 之十九:Selenium +phantomjs 利用 pyquery抓取超级TV网数据
一.介绍 本例子用Selenium +phantomjs爬取超级TV(http://www.chaojitv.com/news/index.html)的资讯信息,输入给定关键字抓取资讯信息. 给定关键 ...
- [Python爬虫] 之三十一:Selenium +phantomjs 利用 pyquery抓取消费主张信息
一.介绍 本例子用Selenium +phantomjs爬取央视栏目(http://search.cctv.com/search.php?qtext=消费主张&type=video)的信息(标 ...
- [Python爬虫] 之二十九:Selenium +phantomjs 利用 pyquery抓取节目信息信息
一.介绍 本例子用Selenium +phantomjs爬取节目(http://tv.cctv.com/epg/index.shtml?date=2018-03-25)的信息 二.网站信息 三.数据抓 ...
随机推荐
- 超详细saltstack安装部署及应用
1.环境准备 准备两台虚拟机 主机名 ip role linux-node1 10.0.0.7 master linux-node2 10.0.0.8 minion 在节点1上安装 master 和 ...
- Photoshop CC 2015
1.Ctrl 加 + -号实现放大缩小2.Ctrl+T 自由变换3.Ctrl+D 取消选区,再选择处理完后想要选中别的区域的话要取消之前选中的区域,要不然之前的区域一直都是选中状态4.F12 将文件恢 ...
- Go语言,用原子函数atomic避免资源竞争
下一步应该是互斥锁了. package main import ( "fmt" "runtime" "sync" "sync/at ...
- iOS运行时,如何增加成员变量
必须实现getter和setter方法 ``` - (void)setName:(NSString *)name { /** * 为某个类关联某个对象 * * @param object#> 要 ...
- Ubuntu 16.04下开启Mysql 3306端口远程访问
原文地址:传送门 0. 前言 网上看到很多开启Mysql远程访问端口,修改的配置文件我都没有找到. 特意查看了我的Linux版本 $ sudo lsb_release -a 显示如下: Distrib ...
- HDU 2199 Can you solve this equation? 【浮点数二分求方程解】
Now,given the equation 8x^4 + 7x^3 + 2x^2 + 3x + 6 == Y,can you find its solution between 0 and 100; ...
- ipython notebook install
1.python install (ubuntut系统默认2.7.x) Github: https://github.com/ipython/ipython 2.sudo apt-get instal ...
- POJ2513Colored Sticks(欧拉通路)(字典树)(并查集)
Colored Sticks Time Limit: 5000MS Memory ...
- ASP.NET Core 2.2 基础知识(十) Web服务器 - Kestrel
ASP.NET Core 应用与进程内的 HTTP 服务器实现一起运行.该服务器实现侦听 HTTP 请求,并在一系列请求功能被写到 HttpContext 时,将这些请求展现到应用中. ASP.NET ...
- HDUOJ题目HTML的爬取
HDUOJ题目HTML的爬取 封装好的exe/app的GitHub地址:https://github.com/Rhythmicc/HDUHTML 按照系统选择即可. 其实没什么难度,先爬下来一个题目的 ...