栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

多线程如何在python3爬虫中调用函数?

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

多线程如何在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 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爬虫中调用。这两个函数我们之前也提到过不少次,想具体了解使用的可以看看之前的讲解。更多Python学习指路:PyThon学习网教学中心。


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/11803.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号