#coding=utf-8
import requests
import re,os,time,ConfigParser
from selenium import webdriver
from multiprocessing.dummy import Pool

######单进程#####

#创建保存截图的目录

def createImagesPath():
    dirname=os.path.dirname(os.path.abspath(__file__)) 
    #print dirname
    imges_path=os.path.join(dirname,time.strftime("%Y%m%d")) 
    #print imges_path
    try:
        if not os.path.exists(imges_path):
            os.mkdir(imges_path)   
        print u"截图保存的目录:",imges_path
        return imges_path 
    except Exception,e:
        print e

#从文件中获取要爬的网站地址
def getWebUrls(web_urls_file_path):
    web_urls=[]
    try:
        with open(web_urls_file_path) as fp:  
            lines=fp.readlines() 
        for line in lines: 
            if line.strip():
                web_urls.append(line.strip()) 
        return web_urls 
    except Exception,e:
        print e

#获取单个网站的所有有效链接
def getLinks(web_url):
    try:
        response=requests.get(web_url) 
        #print response
        html=response.text
        links=re.findall(r'href="(.*?)"',html)
        valid_links=[]
        invalid_links=[]     
        for link in links:  
            if link.strip().startswith("//"):   
                valid_links.append("http:"+link.strip())
            elif link.strip()=="" or link.strip()=="#" or link.strip()=="/" or link.strip().count("javascript")>=1 or link.strip().count("mailto:") >= 1:   
                invalid_links.append(link)
            elif re.search(r"(\.jpg)|(\.jpeg)|(\.gif)|(\.ico)|(\.png)|(\.js)|(\.css)$",link.strip()) or re.match(r'/[^/].*',link.strip()):
                invalid_links.append(link)
            else:
                valid_links.append(link.strip())
        valid_links=list(set(valid_links))  
        return valid_links     
    except Exception,e:
        print e

#保存有效的链接到.txt文件
def saveLinks(links):
    dirname=os.path.dirname(os.path.abspath(__file__)) 
    #print dirname
    links_path=os.path.join(dirname,time.strftime("%Y%m%d")) 
    #print links_path
    try:
        if not os.path.exists(links_path):
            os.mkdir(links_path)   
        links_file_path=os.path.join(links_path,"links.txt")
        print u"链接保存的路径:",links_file_path   
        with open(links_file_path,"w") as fp: 
            fp.writelines([link+"\n" for link in links])   
    except Exception,e:
        print e

#模拟浏览器打开链接并保存截图
class OpenLinkAndSaveImg(object):
    def __init__(self,browser_type):
        try:
            configFilePath=os.path.dirname(os.path.abspath(__file__))+"\\browserAndDriver.ini"
            print u"浏览器驱动配置文件路径:",configFilePath  
            cf=ConfigParser.ConfigParser()
            cf.read(configFilePath)
            browser_type=browser_type.strip().lower()
            driver_path=cf.get("browser_driver",browser_type.strip()).strip()
            print u"浏览器:%s ,驱动位置:%s"%(browser_type,driver_path)
            if browser_type=="ie":
                self.driver=webdriver.Ie(executable_path=eval(driver_path))
            elif browser_type=="chrome":
                self.driver=webdriver.Chrome(executable_path=eval(driver_path))
            elif browser_type=="firefox":
                self.driver=webdriver.Firefox(executable_path=eval(driver_path))
            else:
                print "invalid browser!"
        except Exception,e:
            print e
   
    #打开链接并保存截图
    def openLinkAndSaveImg(self,link_index_imgspath): 
        try:
            link,index,imgspath=link_index_imgspath   
            self.driver.get(link)   
            self.driver.maximize_window()   
            self.driver.get_screenshot_as_file(os.path.join(imgspath,str(index+1)+".png"))
        except Exception,e:
            print e
 
    def end(self):
        self.driver.quit()

if __name__=="__main__":

#单进程
    imgs_path=createImagesPath()
    #weburls=getWebUrls(r"e:\\urls.txt")
    weburls=getWebUrls(os.path.dirname(os.path.abspath(__file__))+"\\urls.txt")
    links=[]    
    start_time=time.time()
    for weburl in weburls:
        links+=getLinks(weburl)
    print u"链接数:%s ;获取所有链接耗时:%s"%(len(links),time.time()-start_time)
    saveLinks(links)
    start_time1=time.time()
    open_link_and_save_img=OpenLinkAndSaveImg("ie")
    for i in range(len(links)):
        open_link_and_save_img.openLinkAndSaveImg((links[i],i,imgs_path))
    open_link_and_save_img.end()
    print u"单进程打开所有链接并截图耗时耗时:",time.time()-start_time1

######多线程(线程池并发执行)######

#coding=utf-8
import requests
import re,os,time,ConfigParser
from selenium import webdriver
from multiprocessing.dummy import Pool

#创建保存截图的目录
def createImagesPath():
    dirname=os.path.dirname(os.path.abspath(__file__)) 
    #print dirname
    imges_path=os.path.join(dirname,time.strftime("%Y%m%d")) 
    #print imges_path
    try:
        if not os.path.exists(imges_path): 
            os.mkdir(imges_path)   
        print u"所有截图保存的目录:",imges_path
        return imges_path 
    except Exception,e:
        print e

#从文件中获取要爬的网站地址
def getWebUrls(web_urls_file_path):
    web_urls=[]
    try:
        with open(web_urls_file_path) as fp:
            lines=fp.readlines() 
        for line in lines: 
            if line.strip():
                web_urls.append(line.strip())  
        return web_urls 
    except Exception,e:
        print e

#获取单个网站的所有有效链接
def getLinks(web_url):
    try:
        response=requests.get(web_url) 
        #print response
        html=response.text
        links=re.findall(r'href="(.*?)"',html)
        valid_links=[]
        invalid_links=[]       
        for link in links:    
            if link.strip().startswith("//"):   
                valid_links.append("http:"+link.strip())
            elif link.strip()=="" or link.strip()=="#" or link.strip()=="/" or link.strip().count("javascript")>=1 or link.strip().count("mailto:") >= 1:   
                invalid_links.append(link)
            elif re.search(r"(\.jpg)|(\.jpeg)|(\.gif)|(\.ico)|(\.png)|(\.js)|(\.css)$",link.strip()) or re.match(r'/[^/].*',link.strip()):
                invalid_links.append(link)
            else:
                valid_links.append(link.strip())
        valid_links=list(set(valid_links))  
        return valid_links     
    except Exception,e:
        print e

#保存有效的链接到.txt文件
def saveLinks(links):
    dirname=os.path.dirname(os.path.abspath(__file__)) 
    #print dirname
    links_path=os.path.join(dirname,time.strftime("%Y%m%d")) 
    #print links_path
    try:
        if not os.path.exists(links_path):
            os.mkdir(links_path)  
        links_file_path=os.path.join(links_path,"links.txt")
        print u"所有链接保存的路径:",links_file_path  
        with open(links_file_path,"w") as fp:   
            fp.writelines([link+"\n" for link in links])   
    except Exception,e:
        print e

#获取浏览器和驱动
def getBrowserAndDriver(browser_type):
    try:
        configFilePath=os.path.dirname(os.path.abspath(__file__))+"\\browserAndDriver.ini"
        print u"浏览器驱动配置文件路径:",configFilePath    
        cf=ConfigParser.ConfigParser()
        cf.read(configFilePath)
        browser_type=browser_type.strip().lower()
        driver_path=cf.get("browser_driver",browser_type.strip()).strip()
        print u"浏览器:%s ,驱动位置:%s"%(browser_type,driver_path)
        return browser_type,driver_path
    except Exception,e:
        print e

#打开链接并保存截图
def openLinkAndSaveImg(browser_driver_link_index_imgspath):  
        try:
            browser,driverpath,link,index,imgspath=browser_driver_link_index_imgspath   
            command="webdriver."+browser.capitalize()+"(executable_path="+driverpath+")"
            driver=eval(command)
            driver.get(link)      
            driver.maximize_window()   
            driver.get_screenshot_as_file(os.path.join(imgspath,str(index+1)+".png"))  
            driver.quit()
        except Exception,e:
            print e

if __name__=="__main__":
    imgs_path=createImagesPath()
    #weburls=getWebUrls(r"e:\\urls.txt")
    weburls=getWebUrls(os.path.dirname(os.path.abspath(__file__))+"\\urls.txt")
    p=Pool(5)
    start_time1=time.time()
    links_list=p.map(getLinks,weburls)
    end_time1=time.time()
    links=[]
    for link_list in links_list:
        links+=link_list
    saveLinks(links)
    print u"链接数:%s ;获取所有链接耗时:%s"%(len(links),end_time1-start_time1)
    browser,driver=getBrowserAndDriver("ie")
    browser_driver_link_index_imgspath=zip([browser]*len(links),[driver]*len(links),links,range(len(links)),[imgs_path]*len(links))
    start_time2=time.time()
    p.map(openLinkAndSaveImg,browser_driver_link_index_imgspath)
    p.close()
    p.join()
    print u"多线程打开所有链接并截图耗时:",time.time()-start_time2

######多线程######

#coding=utf-8
import requests
import re,os,time,ConfigParser
from selenium import webdriver
from multiprocessing.dummy import Pool
import Queue
import threading

#创建保存截图的目录
def createImagesPath():
    dirname=os.path.dirname(os.path.abspath(__file__)) 
    #print dirname
    imges_path=os.path.join(dirname,time.strftime("%Y%m%d")) 
    #print imges_path
    try:
        if not os.path.exists(imges_path):
            os.mkdir(imges_path)   
        print u"所有截图保存的目录:",imges_path
        return imges_path 
    except Exception,e:
        print e

#从文件中获取要爬的网站地址
def getWebUrls(web_urls_file_path):
    web_urls=[]
    try:
        with open(web_urls_file_path) as fp:
            lines=fp.readlines()  
        for line in lines: 
            if line.strip():
                web_urls.append(line.strip())
        return web_urls 
    except Exception,e:
        print e

#获取单个网站的所有有效链接
def getLinks(web_url):
    try:
        response=requests.get(web_url) 
        #print response
        html=response.text
        links=re.findall(r'href="(.*?)"',html)
        valid_links=[]
        invalid_links=[]       
        for link in links:      
            if link.strip().startswith("//"):   
                valid_links.append("http:"+link.strip()) 
            elif link.strip()=="" or link.strip()=="#" or link.strip()=="/" or link.strip().count("javascript")>=1 or link.strip().count("mailto:") >= 1:   
                invalid_links.append(link)
            elif re.search(r"(\.jpg)|(\.jpeg)|(\.gif)|(\.ico)|(\.png)|(\.js)|(\.css)$",link.strip()) or re.match(r'/[^/].*',link.strip()):
                invalid_links.append(link)
            else:
                valid_links.append(link.strip())
        valid_links=list(set(valid_links)) 
        return valid_links     
    except Exception,e:
        print e

#保存有效的链接到.txt文件(当前目录\年月日\links.txt)
def saveLinks(links):
    dirname=os.path.dirname(os.path.abspath(__file__)) 
    #print dirname
    links_path=os.path.join(dirname,time.strftime("%Y%m%d")) 
    #print links_path
    try:
        if not os.path.exists(links_path):  
            os.mkdir(links_path)   
        links_file_path=os.path.join(links_path,"links.txt") 
        print u"所有链接保存的路径:",links_file_path  
        with open(links_file_path,"w") as fp:   
            fp.writelines([link+"\n" for link in links])   
    except Exception,e:
        print e

#多线程
class MyThread(threading.Thread):
    def __init__(self,browser,queue):
        threading.Thread.__init__(self)
        self.queue=queue
        try:
            configFilePath=os.path.dirname(os.path.abspath(__file__))+"\\browserAndDriver.ini"
            #print u"浏览器驱动配置文件路径:",configFilePath
            cf=ConfigParser.ConfigParser()
            cf.read(configFilePath)
            browser_type=browser.strip().lower()
            driver_path=cf.get("browser_driver",browser_type.strip()).strip()
            #print u"浏览器:%s ,驱动位置:%s"%(browser_type,driver_path)
            if browser_type=="ie":
                self.driver=webdriver.Ie(executable_path=eval(driver_path))
            elif browser_type=="chrome":
                self.driver=webdriver.Chrome(executable_path=eval(driver_path))
            elif browser_type=="firefox":
                self.driver=webdriver.Firefox(executable_path=eval(driver_path))
            else:
                print "invalid browser!"

except Exception,e:
            print e

def run(self):
        print "Starting"+self.name
        openLinkAndSaveImg(self.driver,self.queue)
        self.driver.quit()

#打开链接并保存截图
def openLinkAndSaveImg(driver,queue):  
        while not queue.empty():
            queueLock.acquire()
            link_index_imgspath=queue.get()
            queueLock.release()
            try:             
                link,index,imgspath=link_index_imgspath   
                driver.get(link)     
                driver.maximize_window()  
                driver.get_screenshot_as_file(os.path.join(imgspath,str(index+1)+".png"))
            except Exception,e:
                print e

if __name__=="__main__":
    #多线程
    imgs_path=createImagesPath()
    #weburls=getWebUrls(r"e:\\urls.txt")
    weburls=getWebUrls(os.path.dirname(os.path.abspath(__file__))+"\\urls.txt")
    p=Pool(5)
    start_time1=time.time()
    links_list=p.map(getLinks,weburls)
    end_time1=time.time()
    links=[]
    for link_list in links_list:
        links+=link_list
    saveLinks(links)
    print u"链接数:%s ;获取所有链接耗时:%s"%(len(links),end_time1-start_time1)

link_index_imgspath=zip(links,range(len(links)),[imgs_path]*len(links))
    
    queueLock=threading.Lock()
    threads=[]
    link_index_imgspath_Queue=Queue.Queue(len(links))
    for element in link_index_imgspath:
        link_index_imgspath_Queue.put(element)

start_time2=time.time()

for i in range(5):
        thread=MyThread("ie",link_index_imgspath_Queue)
        thread.start()
        threads.append(thread)

for t in threads:
        t.join()

print u"多线程打开所有链接并截图耗时:",time.time()-start_time2

print "end!"

用单进程、多线程并发、多线程分别实现爬一个或多个网站的所有链接,用浏览器打开所有链接并保存截图 python的更多相关文章

  1. 【Python数据分析】Python3多线程并发网络爬虫-以豆瓣图书Top250为例

    基于上两篇文章的工作 [Python数据分析]Python3操作Excel-以豆瓣图书Top250为例 [Python数据分析]Python3操作Excel(二) 一些问题的解决与优化 已经正确地实现 ...

  2. Python 多线程并发程序设计与分析

    多线程并发程序设计与分析 by:授客 QQ:1033553122 1.技术难点分析与总结 难点1:线程运行时,运行顺序不固定 难点2:同一段代码,再不加锁的情况下,可能被多个线程同时执行,这会造成很多 ...

  3. 多线程并发同一个表问题(li)

    现有数据库开发过程中对事务的控制.事务锁.行锁.表锁的发现缺乏必要的方法和手段,通过以下手段可以丰富我们处理开发过程中处理锁问题的方法.For Update和For Update of使用户能够锁定指 ...

  4. Java面试题整理一(侧重多线程并发)

    1..是否可以在static环境中访问非static变量? 答:static变量在Java中是属于类的,它在所有的实例中的值是一样的.当类被Java虚拟机载入的时候,会对static变量进行初始化.如 ...

  5. Java多线程-并发容器

    Java多线程-并发容器 在Java1.5之后,通过几个并发容器类来改进同步容器类,同步容器类是通过将容器的状态串行访问,从而实现它们的线程安全的,这样做会消弱了并发性,当多个线程并发的竞争容器锁的时 ...

  6. HashMap多线程并发问题分析

    转载: HashMap多线程并发问题分析 并发问题的症状 多线程put后可能导致get死循环 从前我们的Java代码因为一些原因使用了HashMap这个东西,但是当时的程序是单线程的,一切都没有问题. ...

  7. 用读写锁三句代码解决多线程并发写入文件 z

    C#使用读写锁三句代码简单解决多线程并发写入文件时提示“文件正在由另一进程使用,因此该进程无法访问此文件”的问题 在开发程序的过程中,难免少不了写入错误日志这个关键功能.实现这个功能,可以选择使用第三 ...

  8. WebDriver多线程并发

    要想多线程并发的运行WebDriver,必须同时满足2个条件,首先你的测试程序是多线程,其次需要用到Selenium Server.下载位置如下图: 下载下来后是一个jar包,需要在命令行中运行.里面 ...

  9. 由获取微信access_token引出的Java多线程并发问题

    背景: access_token是公众号的全局唯一票据,公众号调用各接口时都需使用access_token.开发者需要进行妥善保存.access_token的存储至少要保留512个字符空间.acces ...

随机推荐

  1. 16位和32位的80X86汇编语言的区别

    需要注意的是汇编不是一种语言,不同平台有不同的汇编语言对应,因为汇编和操作系统平台相关,所以汇编语言没有移植性.对于IA-32架构平台而言,选用的32位80386汇编语言,也就只说讨论的操作系统平台是 ...

  2. Go语言之函数签名

    使用type关键字进行, 函数类型变量也可以作为函数的参数或返回值. 我觉得属于高级技巧了,初学者可能需要很多代码实现的, 高级的就可以更通用的实现. package main import &quo ...

  3. Caused by: java.net.ConnectException: Connection refused: master/192.168.3.129:7077

    1:启动Spark Shell,spark-shell是Spark自带的交互式Shell程序,方便用户进行交互式编程,用户可以在该命令行下用scala编写spark程序. 启动Spark Shell, ...

  4. spring的4种事务特性,5种隔离级别,7种传播行为

    spring事务:  事务: 事务逻辑上的一组操作,组成这组操作的各个逻辑单元,要么一起成功,要么一起失败. 事务特性(4种): 原子性 (atomicity):强调事务的不可分割. 一致性 (con ...

  5. Introduction to boundary integral equations in BEM

    Boundary element method (BEM) is an effective tool compared to finite element method (FEM) for resol ...

  6. sendEmail 阿里云使用587端口

    使用sendEmail使用参数   -o tls=yes -s smtp服务器+端口 因为阿里云屏蔽了25端口,我使用465也不成功,只有使用587端口,我使用的qq企业邮箱,测试可用

  7. Python Web开发问题收集(二)

  8. BZOJ4553/洛谷P4093 [HEOI2016/TJOI2016]序列 动态规划 分治

    原文链接http://www.cnblogs.com/zhouzhendong/p/8672434.html 题目传送门 - BZOJ4553 题目传送门 - 洛谷P4093 题解 设$Li$表示第$ ...

  9. BZOJ1131 [POI2008]Sta 其他

    原文链接http://www.cnblogs.com/zhouzhendong/p/8081100.html 题目传送门 - BZOJ1131 题意概括 给出一个N个点的树,找出一个点来,以这个点为根 ...

  10. 058 kafka与log4j集成

    1.首先在resources下面写log4j.properties 主要是因为kafka.producer.KafkaLog4jAppender类的存在. log4j.rootLogger=INFO, ...