• [Python爬虫] 之十一:Selenium +phantomjs抓取活动行中会议活动信息


      一、介绍

        本例子用Selenium +phantomjs爬取活动行(http://www.huodongxing.com/search?qs=数字&city=全国&pi=1)的资讯信息,输入给定关键字抓取资讯信息。

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

        抓取信息内如下:

          1、资讯标题

          2、资讯链接

          3、资讯时间

          4、资讯来源

     

      二、网站信息

        

        

        

        

          

       

      三、数据抓取

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

        1、首先抓取信息列表

          抓取代码:Elements = doc('ul[class="event-horizontal-list-new"]').find('li')

        2、抓取标题

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

        3、抓取链接

          抓取代码:url = 'http://www.huodongxing.com' + element('a').attr('href')

        4、抓取日期

          抓取代码:strdate = element.find('div').eq(0).text().encode('utf8').strip()

        5、抓取主办方

          抓取代码:orgnizer = element('div').eq(2).find('a').eq(1).find('span').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
    from selenium.webdriver.common.action_chains import ActionChains
    import IniFile
    # from threading import Thread
    from pyquery import PyQuery as pq
    import LogFile
    import mongoDB
    import urllib
    class huodongxingSpider(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.db = mongoDB.mongoDbBase()
            self.keyword_list = cf.GetValue("section", "meeting_keywords").split(';')
            websearch_url = cf.GetValue("huodongxing", "websearchurl")
            self.start_urls = []
            for keyword in self.keyword_list:
                for i in xrange(1,4):
                    url = websearch_url + '&pi=' + str(i) + '&qs=' + urllib.quote(keyword)
                    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: 三种格式 '2017.04.27 ~ 04.28'; '2017.04.20  08:30 ~ 12:30' ; '2015.12.29 ~ 2016.01.03'
            :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(strDate[0], currentDate) > 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="event-horizontal-list-new"]').find('li')
    
                for element in Elements.items():
                    strdate = element.find('div').eq(0).text().encode('utf8').strip()
                    flag, date = self.date_isValid(strdate)
                    if flag:
                        title = element('h3').find('a').text().encode('utf8').strip()
                        for keyword in self.keyword_list:
                            if title.find(keyword) > -1:
                                url = 'http://www.huodongxing.com' + element('a').attr('href')
                                orgnizer = element('div').eq(2).find('a').eq(1).find('span').text().encode('utf8').strip()
                                dictM = {'title': title, 'date': date,
                                         'url': url, 'keyword': keyword,
                                         'startdate': date, 'enddate': date,
                                         'area': '', 'organizer': orgnizer}
                                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)
                        area = dochtml('div[class="address"]').find('a').text().encode('utf8').strip()
                        item['area'] = area
    
                        # self.log.WriteLog('title:%s' % title)
                        # self.log.WriteLog('url:%s' % url)
                        # self.log.WriteLog('orgnizer:%s' % orgnizer)
                        # self.log.WriteLog('kword:%s' % keyword)
                        # self.log.WriteLog('area:%s' % area)
                        # self.log.WriteLog('-----------------------------------')
    
                        self.log_print('title:%s' % item['title'])
                        self.log_print('url:%s' % item['url'])
                        self.log_print('date:%s' % item['date'])
                        self.log_print('orgnizer:%s' % item['organizer'])
                        self.log_print('kword:%s' % item['keyword'])
                        self.log_print('area:%s' % area)
                        self.log_print('--------------------------')
    
                    self.db.SaveMeetings(infoList)
            self.driver.close()
            self.driver.quit()
    
    # obj = huodongxingSpider()
    # obj.scrapy_date()
  • 相关阅读:
    数字配对(bzoj 4514)
    任务查询系统(bzoj 3932)
    楼房重建(bzoj 2957)
    Hotel(poj 3667)
    Can you answer these queries(spoj 1043)
    亚瑟王(bzoj 4008)
    潘多拉的盒子(bzoj 1194)
    Circling Round Treasures(codeforces 375c)
    莫队算法---基础知识介绍(转载)
    HDU 1141---Brackets Sequence(区间DP)
  • 原文地址:https://www.cnblogs.com/shaosks/p/6698316.html
Copyright © 2020-2023  润新知