# 本程序为爬虫学习代码,成功爬取了漫微网站上的全部图片内容
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)