介绍
怎么在Python中使用请求模块下载图片?针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。
<强>示例代码:强>
#,编码:utf - 8 import MySQLdb import 请求 import 操作系统 import 再保险 得到threading import 线程 import datetime header =,{& # 39;用户代理# 39;:,& # 39;Mozilla/5.0, (Windows NT 6.1;, Win64;, x64), AppleWebKit/537.36, (KHTML, like 壁虎),& # 39; ,,,,,& # 39;Chrome/63.0.3239.132 Safari/537.36 & # 39;} 时间=file_path & # 39; F: \ \ mlu2& # 39; if not  os.path.exists (file_path): ,os.mkdir (file_path) class 蜘蛛(对象): ,def __init__(自我,,file_path,,头): self.file_path 才能=file_path self.header 才能=头 ,@staticmethod ,def 计时器(函数): def 才能time_count (* args): ,,start_time =, datetime.datetime.now () ,,func (* args) ,,end_time =, datetime.datetime.now () ,,day =, (end_time 作用;start_time)要擦防晒霜 ,,times =, (end_time 作用;start_time)。 ,,hour =times /, 3600 ,,h =times %, 3600 ,,minute =, h /60 ,,m =, h % 60 ,,second =, m ,,print “爬取完成“ ,,print “一共用时% s天% s时% s分% s秒“,%,(天,小时,分钟,秒) return time_count才能 ,def get_link(自我): 时间=conn 才能;MySQLdb.connect(主机=& # 39;localhost # 39;, ,,,,,,,=3306港 ,,,,,,,用户=& # 39;根# 39; ,,,,,,,passwd=& # 39; 729814 & # 39; ,,,,,,,db=& # 39; mlu # 39; ,,,,,,,charset=& # 39; use utf8 # 39;) 时间=cur 才能;conn.cursor () 时间=sql 才能;& # 39;select image 得到msg limit 100 & # 39;, #,形象为事先爬取存到MySQL的图片链接地址 cur.execute才能(sql) 时间=img_link 才能;cur.fetchall () return img_link才能 ,def 下载(自我,,链接): filename 才能=,re.findall(" # 39;。*/(+) & # 39;,,链接)[0] 尝试才能: ,,pic =, requests.get(链接,,头=self.header) ,,if pic.status_code ==, 200: ,,,with 开放(os.path.join (self.file_path) + os.sep +文件名,& # 39;wb # 39;), as 外交政策: ,,,,fp.write (pic.content) ,,,,fp.close () ,,print “下载完成“ except 才能;Exception  as e: ,,print e ,@timer ,def run_main(自我): 时间=threads 才能;[] 时间=links 才能;self.get_link () for 才能;link 拷贝链接: ,,img =, str(链接[0]) ,,t =,线程(目标=self.download, arg游戏=[img]) ,,t.start () ,,threads.append (t) for 才能;t 拷贝线程: ,,t.join () 时间=spider 蜘蛛(file_path,头) spider.run_main ()
关于怎么在Python中使用请求模块下载图片问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注行业资讯频道了解更多相关知识。