python --selenium+phantomjs爬取動態網頁面廣告源碼

來源:互聯網
上載者:User

標籤:監控   python   爬蟲   

背景:利用爬蟲,爬取網站頁面廣告元素,監控爬取元素的數目,定時發送監控郵件

#!/usr/bin/env python2.7# -*- coding: utf-8 -*-‘‘‘@xiayun@[email protected]#爬取網站內容,利用phantomjs:IP代理+修改UA+動態網頁面執行JS‘‘‘from selenium import webdriverfrom selenium.webdriver.common.desired_capabilities import DesiredCapabilitiesimport timeimport urllib,urllib2import smtplibimport refrom email.mime.text import MIMETextfrom email.header import Headerimport sysdef reptile():    global result, data    #proxy_ip.txt為IP代理池,可以自己爬IP,也可以買,不過都不穩定,    #需要在前面再加一個IP驗證程式。    IPS = [i for i in open("./proxy_ip.txt", ‘r‘).readline().split(‘\n‘) if i]    print IPS    for i in IPS:        service_args = []        service_args = [‘--proxy-type=HTTP‘,]        IP_str = ‘‘.join(i)        print IP_str        proxy_IP = ‘--proxy=%s‘ % IP_str        service_args.append(proxy_IP)        dcap = dict(DesiredCapabilities.PHANTOMJS)        #建立UA頭        dcap["phantomjs.page.settings.userAgent"] = (‘Mozilla/5.0 ([email protected];         CPU iPhone OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko)         Version/9.0 Mobile/13B143 Safari/601.1‘)        #利用phantomjs仿瀏覽器動作,參數2是代理IP        driver = webdriver.PhantomJS(desired_capabilities=dcap, service_args=service_args)        #設定訪問逾時時間        driver.implicitly_wait(60)        driver.set_page_load_timeout(60)        try:            driver.get(‘網頁地址‘)        except:            print "timeout"        finally:            data = driver.page_source            time.sleep(20)            req = r"廣告元素"            rule1 = re.compile(req)            lists = re.findall(rule1, data)            counts = len(lists)            print counts            # print data            driver.quit()            #判斷廣告元素是否為22            if counts == 22:                print "The webpage is OK!"                result = "The webpage is OK!Find 22 廣告元素!                proxy_IP:%s " % IP_str                break            if counts != 22:                #IPS.remove(i)                print "%s is bad!" % i.strip()                result = "The webpage maybe bad"    print "close"    #返回結果和網頁代碼    return result, datadef send_mail(result,data):        receivers = [‘[email protected]‘] #接收人    mail_host = ‘smtp.exmail.qq.com‘ #代理郵箱smtp協議    mail_user = ‘[email protected]‘ #發送人    mail_pass = ‘xxxx‘  #密碼    mail_postfix = ‘xxxx‘  #寄件匣的尾碼    title = str(result)    msg = MIMEText(data, ‘plain‘, ‘utf-8‘)  #文字格式設定內容    me = title.decode(‘utf-8‘) + "<" + mail_user + ">"    msg[‘Subject‘] = Header(title, ‘utf-8‘)    msg[‘From‘] = Header(me, ‘utf-8‘)    msg[‘To‘] = Header(";".join(receivers), ‘utf-8‘)    try:        s = smtplib.SMTP()        s.connect(mail_host)        s.login(mail_user, mail_pass)        s.sendmail(me,receivers , msg.as_string())        s.close()        print "發送成功"        return True    except smtplib.SMTPException:        print "Error: 無法發送郵件"        return Falseif __name__ == ‘__main__‘:    while 1:        print ‘start‘ + ‘ ‘ + ‘‘.join(time.ctime(time.time()))        result, data = reptile()        send_mail(result=result, data=data)        print ‘stop‘ + ‘ ‘ + ‘‘.join(time.ctime(time.time()))        time.sleep(600)    sys.exit(0)


本文出自 “echo xiayun” 部落格,請務必保留此出處http://linuxerxy.blog.51cto.com/10707334/1893893

python --selenium+phantomjs爬取動態網頁面廣告源碼

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.