python如何爬取图片存入excel
时间: 2023-07-05 09:05:19 浏览: 183
在Python中,你可以使用第三方库`requests`和`openpyxl`来实现爬取图片并存入Excel中。以下是代码示例:
```python
import requests
from openpyxl import Workbook
from openpyxl.utils import get_column_letter
from openpyxl.drawing.image import Image
# 定义图片链接列表
image_urls = ['https://example.com/image1.jpg', 'https://example.com/image2.jpg', 'https://example.com/image3.jpg']
# 创建Excel工作簿
workbook = Workbook()
worksheet = workbook.active
# 遍历图片链接列表并下载图片
for index, url in enumerate(image_urls):
response = requests.get(url)
image_content = response.content
# 将图片保存到本地
with open(f'image{index + 1}.jpg', 'wb') as image_file:
image_file.write(image_content)
# 将图片插入到Excel中
image = Image(f'image{index + 1}.jpg')
column_letter = get_column_letter(index + 1)
worksheet.column_dimensions[column_letter].width = 25
worksheet.row_dimensions[index + 1].height = 100
worksheet.add_image(image, f'{column_letter}{index + 1}')
# 保存Excel文件
workbook.save('images.xlsx')
```
这个代码示例假设你已经准备好要爬取的图片链接列表,并且这些链接都是以`.jpg`结尾的图片文件。如果你需要爬取其他类型的图片文件,你需要相应地修改代码。
此外,这个代码示例将每个图片都保存到本地,并将其插入到Excel中。如果你不需要保存图片到本地,只需要将`Image`对象直接插入到Excel中即可。
阅读全文
相关推荐













