温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

多线程在python3爬虫中调用函数的示例

发布时间:2020-11-25 09:32:57 来源:亿速云 阅读:232 作者:小新 栏目:编程语言

小编给大家分享一下多线程在python3爬虫中调用函数的示例,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!

可以说函数和python爬虫一般情况下都可以结合使用,但是这需要小伙伴们对于函数的使用方法进行充分的了解,才能和python爬虫的知识点紧密结合使用。经过几天多线程和爬虫的内容讲解,相信大家对于这方面的模块内容已经比较熟悉的,所以可以用我们的老朋友download()函数进行一次知识点的交流,下面就来来看看download()在python爬虫中的运用吧。

对其进行构造,创建日志,download()函数创建线程,update_queque_url对连接的列表进行更新,get_url()根据bs4进行匹配获取连接,download_all()通过调用download()函数实现批量下载。spider作为一个入口函数进行爬取

class Crawler:
    def __init__(self,name,domain,thread_number):
        self.name=name
 
        self.domain=domain
        self.thread_number=thread_number
 
        self.logfile=open('log.txt','w')
        self.thread_pool=[]
        self.url = 'http://'+domain
 
     def spider(self):# 内容会随着爬虫的进行而更新
        global g_queue_urls# 初始,队列中仅有一个url
        g_queue_urls.append(self.url)# 爬取的深度
        depth =0
        print(f'爬虫{self.name}开始启动........')
        while g_queue_urls:
            depth +=1
            print(f'当前爬取深度是{depth}')
            self.logfile.write(f'URL:{g_queue_urls[0]}')
            self.download_all() # 下载所有
            self.update_queque_url() # 更新 url队列
            self.logfile.write(f">>>Depth:{depth}")
            count = 0
            while count <len(g_queue_urls):
                self.logfile.write(f"累计爬取{g_total_count}条,爬取是第{g_queue_urls[count]}个")
                count+=1
 
 
 
    def download_all(self):
        global g_queue_urls
        global g_total_count
        i=0
        while i < len(g_queue_urls):
            j=0
            while j<self.thread_number and i+j <len(g_queue_urls):
                g_total_count +=1
                print(g_queue_urls[i+j])
                thread_result=self.download(g_queue_urls[i+j],f"{g_total_count}.html",j)
                if thread_result  is not None:
                      print(f'线程{i+j}启动')
                j +=1
            i=i+j
            for thread in self.thread_pool:
                thread.join(25)
        g_queue_urls=[]
 
 
 
    def download(self,url,filename,tid):
        print(url,filename,tid)
        creawler_thread= CrawlerThread(url,filename,tid)
        self.thread_pool.append(creawler_thread)
        creawler_thread.start()
    def update_queque_url(self):
        global g_queue_urls
        global g_exist_urls#已经爬过的url
        new_urls=[]#新发现的url
        for url_content in g_urls:
            new_urls +=self.get_Url(url_content)# 从页面中提取新url
        g_queue_urls=list(set(new_urls)  -set(g_exist_urls)) # 去除重复的和已经爬过的
 
    def get_Url(self,content):
     '''
        从网页源代码中提取url
        '''
        links =[] # 保存提取到的href
        try:
 
            soup =BeautifulSoup(content)
            for link in soup.findAll('a'):
                if link is not None and link.get('href') is not None:
                    if self.domain in link['href']:
    # 如果link是本网站的绝对地址
                        links.append(link)
                    elif  len(link['href']) >10 and  'http://' not in link['href']:
 # 如果link是相对地址
                        links.append(self.url +link['href'])
 
 
 
        except Exception as e:
            print("fail to get url",e)
        return links

主函数调用爬虫函数的spider()方法

if __name__=="__main__":
    domain ="www.geyanw.com"
    thread_number=10
    name="geyan"
    crawler =Crawler(name,domain,thread_number)
    crawler.spider()

除了download()函数,spider()也可以在python爬虫中调用。

以上是“多线程在python3爬虫中调用函数的示例”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI