python爬虫,一段完整的python爬虫批量下载网站图片资源的代码
# 本程序为爬虫学习代码,成功爬取了漫微网站上的全部图片内容
import re
import os
import requests
def getHTMLText(url):
try:
r=requests.get(url)
r.raise_for_status()
r.encoding=r.apparent_encoding
return r.text
except:
print("request failed")
url = ‘http://marvel.mtime.com/‘ # 漫微网址
web_data = getHTMLText(url) # web_data保存目标url的html代码内容
res = re.compile(r‘src="(.+?.jpg)"‘) # 定义查询规则,所有以src开头,中间包含任意多个字符的,并且结尾为.jpg的文件被
#提取并保存
reg = re.findall(res, web_data) # 在web_data中找到并提取满足res规则的全部字符串,并保存在reg列表
for i in reg:
target_url = url + i # 变量target_url获得图片的url
try:
pic = requests.get(target_url).content # 从target_url下载了图片,并以二进制的形式保存在变量pic中
except:
print(target_url + ‘can not open‘)
res = re.compile(r‘images/(.+?.jpg)‘)
pic_name = re.findall(res, i)[0] #提取图片文件名,从结果数组第[0]个元素获得具体文件名
print(pic_name)
with open(pic_name, ‘wb‘) as f:
f.write(pic) 相关推荐
sunzhihaofuture 2020-07-19
sunzhihaofuture 2020-06-06
oXiaoChong 2020-06-05
ARCXIANG 2020-06-05
夜斗不是神 2020-11-17
染血白衣 2020-11-16
ARCXIANG 2020-11-02
CycloneKid 2020-10-27
meylovezn 2020-08-28
囧芝麻 2020-08-17
数据挖掘工人 2020-08-15
cxcxrs 2020-07-28
dashoumeixi 2020-07-20