python爬图片代码
时间: 2023-09-26 09:05:49 浏览: 42
以下是一个简单的 Python 爬取图片的代码:
```python
import requests
import os
url = "http://example.com/image.jpg" # 图片的URL地址
path = "/path/to/save/image.jpg" # 保存图片的路径
# 发送HTTP GET请求,获取图片内容
response = requests.get(url)
# 如果请求成功,将图片保存到本地文件系统中
if response.status_code == 200:
with open(path, "wb") as f:
f.write(response.content)
print("图片已保存到", path)
else:
print("请求出错,HTTP状态码:", response.status_code)
```
注意,这只是一个基本的示例代码,实际使用中需要根据具体网站的特点和需求进行修改。另外,爬取网站上的图片时,需要注意版权问题和网站的使用规定,遵守相关法律法规。
相关问题
python爬虫图片代码
以下是一个Python爬虫图片的代码示例:
```python
import requests
import re
import urllib
from io import BytesIO
from PIL import Image
def get_pictures(url):
data = requests.get(url).text
regex = r'<img src="(.*?.jpg)"'
pa = re.compile(regex)
images = re.findall(pa, data)
i = 0
print('*****Starting*****')
for image in images:
if '" data-original="' in image:
address = image.split('" data-original="')[1]
else:
address = image
i += 1
image = requests.get(address)
image = Image.open(BytesIO(image.content))
image.save('D:\\111\\' + str(i) + '.jpg')
print("*****Ending*****")
if __name__ == '__main__':
url = "http://soso.nipic.com/q_中国交通and隧道景观_g_0.html"
get_pictures(url)
print("OK!!!")
```
Python爬虫图片的代码
当爬取网页中的图片时,我们需要用到Python中的requests库和BeautifulSoup库,下面是一个简单的Python爬虫图片的代码示例:
``` python
import requests
from bs4 import BeautifulSoup
# 定义要爬取的URL地址
url = "https://www.example.com"
# 发送请求并获取页面内容
response = requests.get(url)
html = response.content
# 使用BeautifulSoup库解析页面内容
soup = BeautifulSoup(html, 'html.parser')
img_tags = soup.find_all('img')
# 遍历所有的图片标签,获取图片链接并下载
for img in img_tags:
img_url = img.get('src')
# 使用requests库发送请求并下载图片
img_data = requests.get(img_url).content
with open('image_name.jpg', 'wb') as handler:
handler.write(img_data)
# 下载完成提示
print("所有图片已经下载完成!")
```
这是一个简单的爬虫示例,实际情况中还需要加入错误处理、多线程下载等功能,以提高代码的鲁棒性和效率。