一、介绍

    本例子用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氪网站数据的更多相关文章

  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://www.toutiao.com/search/?keyword=电视)的资讯信息,输入给定关键字抓取资讯信息. 给定 ...

  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://www.tvhome.com/news/)的资讯信息,输入给定关键字抓取图片信息. 给定关键字:数字:融合:电视 ...

  6. [Python爬虫] 之二十四:Selenium +phantomjs 利用 pyquery抓取中广互联网数据

    一.介绍 本例子用Selenium +phantomjs爬取中广互联网(http://www.tvoao.com/select.html)的资讯信息,输入给定关键字抓取资讯信息. 给定关键字:数字:融 ...

  7. [Python爬虫] 之十九:Selenium +phantomjs 利用 pyquery抓取超级TV网数据

    一.介绍 本例子用Selenium +phantomjs爬取超级TV(http://www.chaojitv.com/news/index.html)的资讯信息,输入给定关键字抓取资讯信息. 给定关键 ...

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

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

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

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

随机推荐

  1. 用python写爬虫笔记(一)

    https://bitbucket.org/wswp/code   http://example.webscraping.com http://www.w3schools.com selenium.g ...

  2. Swift开发学习(一):初始篇

    http://blog.csdn.net/powerlly/article/details/29351103 Swift开发学习:初始篇 关于 苹果公司于WWDC2014(Apple Worldwid ...

  3. 【转】针对Android上的ROP攻击剖析

    引言       ROP(Return-oriented programming),即“返回导向编程技术”.其核心思想是在整个进程空间内现存的函数中寻找适合指令片断(gadget),并通过精心设计返回 ...

  4. python学记笔记 2 异步IO

    在IO编程中,我们知道CPU的速度远远快于磁盘,网络IO,在一个线程中,CPU执行速度的代码非常快,然而遇到IO操作就需要阻塞 需要等待IO操作完成才能继续下一步的动作.这种情况叫做同步IO 在IO操 ...

  5. 使用go写一个检测tcpudp状态的包

    使用go写一个检测tcpudp状态的包 http://www.2cto.com/os/201501/367596.html

  6. windows使用celery遇到的错误

    https://www.jianshu.com/p/e5539d96641c 按照这个教程一步步执行到最后报错了. 运行task_dispatcher.py的时候 ValueError: not en ...

  7. junit单元测试+junit与Spring结合

    配置:右键要加入单元测试的工程,选择properties,然后选择java build path,选择add library,选择junit即可. 编写:右键要测试的class,new一个junit ...

  8. javascript中判断变量时变量值为 0 的特殊情况

    有时候我们在js中会直接判断变量是否存在值,下面列举一些情况: var a = 0; var b = 1; var c = ' '; var d; console.log( a ? 1 : null) ...

  9. Selenium2+python自动化67-用例失败自动截图【转载】

    前言: 装饰器其实就是一个以函数作为参数并返回一个替换函数的可执行函数 上一篇讲到用装饰器解决异常后自动截图,不过并没有与unittest结合,这篇把截图的装饰器改良了下,可以实现用例执行失败自动截图 ...

  10. 设置每个datanode里面的map数目,提高运行效率

    首先可以通过hdfs.site.xml下面的dfs.block.size来设置数据的块大小,这个参数会决定map的总数目(4194304=4m) 然后通过mapred.site.xml下面的mapre ...