一、介绍

    本例子用Selenium +phantomjs爬取电视之家(http://www.tvhome.com/news/)的资讯信息,输入给定关键字抓取资讯信息。

    给定关键字:数字;融合;电视

    抓取信息内如下:

      1、资讯标题

      2、资讯链接

      3、资讯时间

      4、资讯来源

 

  二、网站信息

    

    

    

      

    

    

  

  三、数据抓取

    针对上面的网站信息,来进行抓取

    1、首先抓取信息列表

      抓取代码:Elements = doc('div[class="main_left fl"]').find('div[class="content"]').find('ul').find('li')

    2、抓取标题

      抓取代码:title = element('h2').find('a').text().encode('utf8').strip()

    3、抓取链接

      抓取代码:url = element('a').attr('href')

    4、抓取日期

      抓取代码:date = element('em[class="em_3"]').text().encode('utf8').strip()

    5、抓取来源

      抓取代码:strSource = dochtml('span[class="aside01"]').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 mongoDBclass tvhomeSpider(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("tvhome", "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 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) / 86400return resultdef date_isValid(self, strDateText):'''判断日期时间字符串是否合法:如果给定时间大于当前时间是合法,或者说当前时间给定的范围内:param strDateText: '2017-06-20 10:22 ':return: True:合法;False:不合法'''currentDate = time.strftime('%Y-%m-%d')datePattern = re.compile(r'\d{4}-\d{2}-\d{2}')strDate = re.findall(datePattern, strDateText)if len(strDate) == 1:if self.Comapre_to_days(currentDate, strDate[0]) == 0:return True, strDate[0]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)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('div[class="main_left fl"]').find('div[class="content"]').find('ul').find('li')for element in Elements.items():date = element('em[class="em_3"]').text().encode('utf8').strip()flag, strDate = self.date_isValid(date)if flag:title = element('h2').find('a').text().encode('utf8').strip()for keyword in self.keyword_list:if title.find(keyword) > -1:url = element('a').attr('href')dictM = {'title': title, 'date': strDate,'url': url, 'keyword': keyword, 'introduction': title, 'source': ''}infoList.append(dictM)breakif len(infoList)>0:for item in infoList:url =item['url']self.driver.get(url)htext = self.driver.execute_script("return document.documentElement.outerHTML")dochtml = pq(htext)strSource = dochtml('span[class="aside01"]').text().encode('utf8').strip()item['source'] = strSourceself.log_print('title:%s' % item['title'])self.log_print('url:%s' % item['url'])self.log_print('date:%s' % item['date'])self.log_print('source:%s' % item['source'])self.log_print('kword:%s' % item['keyword'])self.log_print(strsplit)# self.db.SaveInformations(infoList)
self.driver.close()self.driver.quit()obj = tvhomeSpider()
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爬取界面(https://a.jiemian.com/index.php?m=search&a=index&type=news& ...

  3. [Python爬虫] 之二十七:Selenium +phantomjs 利用 pyquery抓取今日头条视频

    一.介绍 本例子用Selenium +phantomjs爬取今天头条视频(http://www.tvhome.com/news/)的信息,输入给定关键字抓取图片信息. 给定关键字:视频:融合:电视 二 ...

  4. python爬虫成长之路(一):抓取证券之星的股票数据

    python爬虫成长之路(一):抓取证券之星的股票数据 获取数据是数据分析中必不可少的一部分,而网络爬虫是是获取数据的一个重要渠道之一.鉴于此,我拾起了Python这把利器,开启了网络爬虫之路. 本篇 ...

  5. python抓取数据包_利用python-pypcap抓取带VLAN标签的数据包方法

    1.背景介绍 在采用通常的socket抓包方式下,操作系统会自动将收到包的VLAN信息剥离,导致上层应用收到的包不会含有VLAN标签信息.而libpcap虽然是基于socket实现抓包,但在收到数据包 ...

  6. Python爬虫之XPath基础教程:用代码抓取网页数据

    Python爬虫之XPath基础教程:用代码抓取网页数据 在网络时代,网页数据是获取信息和进行分析的最重要的来源之一.Python的爬虫技术让我们可以轻松抓取网页数据,并进行数据处理.XPath是一种 ...

  7. Python进阶之Scrapy利用ImagesPipeline抓取汽车之家宝马5系缩略图

    Python进阶之Scrapy利用ImagesPipeline抓取汽车之家宝马5系缩略图 1. 创建项目 2. 使用ImagesPipeline爬取数据 items.py setings.py aut ...

  8. python 模拟浏览器selenium_Python使用Selenium模块模拟浏览器抓取斗鱼直播间信息示例...

    本文实例讲述了Python使用Selenium模块模拟浏览器抓取斗鱼直播间信息.分享给大家供大家参考,具体如下: import time from multiprocessing import Poo ...

  9. Python爬虫实战02:分析Ajax请求并抓取今日头条街拍

    1 目标网站分析 首先我们打开今日头条网站,搜索 街拍,点击图集,这里每就是我们要爬取的目录,我们称为索引页.1 点开一个标题,进去,称为详情页.2这里面的图是我们所要爬取的.比如这里可以点击图片,共 ...

最新文章

  1. RxJava 变换操作符Map
  2. linux7.4 配置yum,Centos7.4重装yum
  3. ORA-00119,ORA-00132 错误处理
  4. python如何互换_python中怎么交换列的顺序
  5. almost a hero 差不多英雄 攻略
  6. 根据身份证号计算周岁年龄
  7. 【截屏、录屏】工具分享-最简单的工具-QQ
  8. C语言入门130题-OJ
  9. 新安装的Eclipse,出现英文乱码,标题窗口英文乱码,打开的Java类窗口显示名称出现乱码
  10. 大学英语A4 | 上海师范大学慕课《英汉互译》笔记
  11. CSS中的传统布局、多列布局、弹性伸缩布局及Emmet工具
  12. 如何帮银行保持长期竞争力?融360天机公布独家秘诀
  13. 委外采购订单 Subcontract PO
  14. 在EPICS定义一个新的记录类型
  15. Web前端基础笔记:第十章 CSS-背景
  16. Dubbo2.7.3入门
  17. 物联网卡发展历程与发展趋势
  18. Java开发游戏脚本(第五卷)
  19. java 播放mid_今天编辑了一个播放mid音乐的程序,呵呵,,分享一下我的快乐!...
  20. adams2005软件下载

热门文章

  1. Symbian S60 签名工具
  2. 互联网巨头布阵LoRaWAN,是又一春天还是不容乐观?
  3. MapReduce编程(四) 求均值
  4. Python基础-三次用户验证登录购买商品程序
  5. Python基础学习:svn导出差异文件脚本
  6. 对Repository模式误用的反思和纠正
  7. 沣西新城大数据产业园:打造大数据全生态链
  8. 关于group by的用法 原理
  9. 大规模分布式系统资源管理(二)
  10. 手机驱动开发_新加坡科学家开发由智能手机驱动的无电池“智能服装”