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

  一、介绍

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

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

    抓取信息内如下:

      1、资讯标题

      2、资讯链接

      3、资讯时间

      4、资讯来源

 

  二、网站信息

    

    

    

    

  

  三、数据抓取

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

    1、首先抓取信息列表

      抓取代码:Elements = doc(‘ul[class="la_list"]‘).find(‘li‘)

    2、抓取标题

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

    3、抓取链接

      抓取代码:url = element(‘h4‘).find(‘a‘).attr(‘href‘)

    4、抓取日期

      抓取代码:date = element(‘div[class="time"]‘).find(‘span‘).text().encode(‘utf8‘).strip()

    5、抓取来源

      抓取代码:strSources = dochtml(‘span[class="wzof"]‘).text().encode(‘utf8‘).strip().split(‘:‘)

  

  四、完整代码

# 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

class chaojitvSpider(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("chaojitv", "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) / 86400
        return result

    def 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(‘ul[class="la_list"]‘).find(‘li‘)
            for element in Elements.items():
                date = element(‘div[class="time"]‘).find(‘span‘).text().encode(‘utf8‘).strip()
                flag, strDate = self.date_isValid(date)
                if flag:
                    title = element(‘h4‘).find(‘a‘).text().encode(‘utf8‘).strip()
                    for keyword in self.keyword_list:
                        if title.find(keyword) > -1:
                            url = element(‘h4‘).find(‘a‘).attr(‘href‘)
                            dictM = {‘title‘: title, ‘date‘: strDate,
                             ‘url‘: url, ‘keyword‘: keyword, ‘introduction‘: title, ‘source‘: ‘‘}
                            infoList.append(dictM)
                            break
            if 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)
                    strSources = dochtml(‘span[class="wzof"]‘).text().encode(‘utf8‘).strip().split(‘:‘)
                    if len(strSources)>2:
                        item[‘source‘] = strSources[2].replace(‘编辑‘,‘‘).replace(‘ ‘,‘‘)

                    self.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 = chaojitvSpider()
obj.scrapy_date()
时间: 2024-08-24 08:40:23

[Python爬虫] 之十九:Selenium +phantomjs 利用 pyquery抓取超级TV网数据的相关文章

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

一.介绍 本例子用Selenium +phantomjs爬取智能电视网站(http://www.tvhome.com/news/)的资讯信息,输入给定关键字抓取图片信息. 给定关键字:数字:融合:电视 二.网站信息 三.数据抓取 针对上面的网站信息,来进行抓取 1.首先抓取信息列表 抓取代码:Elements = doc('div[class="main_left fl"]').find('div[class="content"]').find('ul').find

[Python爬虫] 之十:Selenium +phantomjs抓取活动行中会议活动(多线程抓取)

延续上个抓取活动行中会议活动的问题,上次使用是单线程的抓取,效率较低,现在使用多线程的抓取. 数据的抓取分为两个过程:首先获取每个关键字搜索结果对应的url和页数,保存在列表里面,这个过程用一个线程来实现(类似生产者),同时根据获取的关键字的url和页数,抓取对应的数据,这个过程用多线程来抓取(类似消费者) 这样整个抓取过程共用了144.366188 秒,采用单线程来进行抓取要用大概184秒,这样大概节省了40秒 具体代码如下: # coding=utf-8import osimport ref

[Python爬虫] 之十三:Selenium +phantomjs抓取活动树会议活动数据

抓取活动树网站中会议活动数据(http://www.huodongshu.com/html/index.html) 具体的思路是[Python爬虫] 之十一中抓取活动行网站的类似,都是用多线程来抓取,但是由于活动树网站 ,每个关键字搜索页的ur是固定,比如搜索“数字”结果有470个结果,没页10条记录,第二页的url和第一页的 url是一样的. 因此针对每个关键字用一个线程进行搜索. 具体代码如下: # coding=utf-8import osimport refrom selenium im

[Python爬虫] 之十一:Selenium +phantomjs抓取活动树中会议活动

最近在抓取活动树网站 (http://www.huodongshu.com/html/find.html) 上数据时发现,在用搜索框输入中文后,点击搜索,phantomjs抓取数据怎么也抓取不到,但是用IE驱动就可以找,后来才发现了原因. 例如URL: http://www.huodongshu.com/html/find_search.html?search_keyword=数字, phantomjs抓取的内存中url变成了http://www.huodongshu.com/html/find

Python爬虫技术干货,教你如何实现抓取京东店铺信息及下载图片

什么是Python爬虫开发 Python爬虫开发,从网站某一个页面(通常是首页)开始,读取网页的内容,找到在网页中的其它链接地址,然后通过这些链接地址寻找下一个网页,这样一直循环下去,直到把这个网站所有的网页都抓取完为止.世界上80%的爬虫是基于Python开发的,学好爬虫技能,可为后续的大数据分析.挖掘.机器学习等提供重要的数据源. Python爬虫实例参考 这是一个用Python爬虫实现抓取京东店铺信息以及下载图片的例子,仅供参考. 信息抓取: 图片下载的:注意: 1.在选择信息的时候用CS

python爬虫入门练习,使用正则表达式和requests爬取LOL官网皮肤

刚刚python入门,学会了requests模块爬取简单网页,然后写了个爬取LOL官网皮肤的爬虫,代码奉上 #获取json文件#获取英雄ID列表#拼接URL#下载皮肤 #导入re requests模块 import requestsimport reimport time def Download_LOL_Skin(): #英雄信息Json文件地址:https://lol.qq.com/biz/hero/champion.js #获取英雄信息列表 json_url = "https://lol.

python爬虫(十九)BeautifulSoup4库

1.BeautifulSoup4库也是一个HTML/XML解析器,主要也是提取数据.lxml只会局部遍历,BeautifulSoup是基于HTML DOM的,会载入整个文档,建立一个树状结构,在解析HTML时比较简单. from bs4 import BeautifulSoup html=" 一段代码" soup=BeautifulSoup(html,'lxml') # 1.获取所有tr标签 trs=soup.find_all('tr') # 2.获取第2个tr标签 # limit表示

selenium和pyquery抓取异步加载数据

from selenium import webdriver from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from pyquery import PyQuery as pq import time #打开不同的浏览

Python进阶(三十九)-数据可视化の使用matplotlib进行绘图分析数据

Python进阶(三十九)-数据可视化の使用matplotlib进行绘图分析数据 ??matplotlib 是python最著名的绘图库,它提供了一整套和matlab相似的命令API,十分适合交互式地进行制图.而且也可以方便地将它作为绘图控件,嵌入GUI应用程序中. ??它的文档相当完备,并且 Gallery页面 中有上百幅缩略图,打开之后都有源程序.因此如果你需要绘制某种类型的图,只需要在这个页面中浏览/复制/粘贴一下,基本上都能搞定. ??在Linux下比较著名的数据图工具还有gnuplot