写一个下载图片的python代码
时间: 2024-03-02 09:42:38 浏览: 24
当然,我可以为您提供如下示例代码:
```python
import requests
url = "https://www.example.com/image.jpg"
response = requests.get(url)
with open("image.jpg", "wb") as f:
f.write(response.content)
print("Image downloaded successfully!")
```
在以上代码中,我们使用了 Python 的 requests 库来从网站下载图片。我们首先指定要下载的图片 URL("https://www.example.com/image.jpg"),然后通过 requests.get 方法发送一个 GET 请求,从服务器获取包含图片数据的响应。接着,我们创建一个名为 image.jpg 的新文件,并将响应内容写入该文件中。下载完成后,我们显示一条消息以通知用户程序已成功地下载了图片。
相关问题
python 写一个爬图片的代码
我可以提供一个Python编写的爬图片代码的示例:# 导入需要的库
import requests
import urllib.request# 定义函数
def get_img_urls(url):
# 获取网页
response = requests.get(url)
html = response.text
# 使用正则表达式解析网页
img_urls = re.findall('img src="(.*?)"',html,re.S)
# 返回图片链接列表
return img_urls# 下载图片
def download_imgs(img_urls, path):
# 定义图片编号
i = 0
# 遍历图片链接列表
for img_url in img_urls:
# 使用urllib.request.urlretrieve() 方法下载图片
urllib.request.urlretrieve(img_url, path + '\%s.jpg' % i)
i += 1# 主函数
if __name__ == '__main__':
# 获取图片链接列表
img_urls = get_img_urls('https://www.example.com')
# 定义存储图片的路径
path = r'C:\Users\xxx\xxx\xxx'
# 下载图片
download_imgs(img_urls, path)
写一个图片读取代码用Python
好的,以下是一个Python代码示例,用于读取图片文件:
```python
from PIL import Image
# 打开图片文件
img = Image.open("example.jpg")
# 显示图片
img.show()
# 获取图片尺寸
width, height = img.size
print("图片尺寸:", width, "x", height)
# 获取像素点信息
pixels = img.load()
print("像素点信息:", pixels[0,0])
```
这个示例代码使用了Python的Pillow库来读取图片文件,首先打开一个名为"example.jpg"的图片文件,然后显示图片、获取图片尺寸和像素点信息。您可以根据需要修改代码来适应您的具体情况。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)