爬虫请求并保存图片

requests 模块的用法

 pic_res = requests.get(url, cookies=cookies, headers=headers)

with open('tmp.jpg', 'wb') as file:
     file.write(pic_res.content)

Scrapy 框架 request 用法

def start_requests(self):
    yield Request(url, cookies=cookies, headers=headers, callback=self.save_pic)

def save_pic(self, response):
    with open('tmp.jpg', 'wb') as file:
        file.write(response.body)
以下是Python爬虫爬取网页图片并保存的代码示例: ```python import requests from bs4 import BeautifulSoup import os # 目标网站 url = "https://unsplash.com/" # 请求头 headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3"} # 发送请求 response = requests.get(url, headers=headers) # 解析网页 soup = BeautifulSoup(response.text, "html.parser") # 获取所有图片标签 img_tags = soup.find_all("img") # 创建保存图片的文件夹 if not os.path.exists("images"): os.mkdir("images") # 遍历图片标签,获取图片链接并保存 for img_tag in img_tags: img_url = img_tag.get("src") if img_url.startswith("https://"): img_response = requests.get(img_url, headers=headers) with open("images/" + img_url.split("/")[-1], "wb") as f: f.write(img_response.content) print("保存成功:", img_url) ``` 解释: 1. 首先导入需要的库:requests发送网络请求、BeautifulSoup解析网页、os创建文件夹等。 2. 定义目标网站的URL和请求头。 3. 使用requests库发送网络请求,获得网页的响应。 4. 使用BeautifulSoup库解析网页,获取所有图片标签。 5. 创建一个名为images的文件夹,用来保存图片。 6. 遍历所有图片标签,获取图片链接,并判断是否为https协议开头的链接。 7. 如果是,使用requests库发送网络请求,获取图片的二进制数据,并将其保存到images文件夹中,以图片的名称命名。 8. 打印保存成功的提示信息。 9. 完成爬取和保存。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值