Python爬虫图片的代码
时间: 2024-05-18 10:09:31 浏览: 12
当爬取网页中的图片时,我们需要用到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("所有图片已经下载完成!")
```
这是一个简单的爬虫示例,实际情况中还需要加入错误处理、多线程下载等功能,以提高代码的鲁棒性和效率。
相关问题
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 爬虫下载图片的代码示例:
```python
import requests
import os
# 如果不存在目标文件夹则创建
if not os.path.exists('images'):
os.makedirs('images')
url = 'https://www.example.com/image.jpg'
response = requests.get(url)
# 获取文件名
filename = url.split('/')[-1]
# 保存图片
with open('images/' + filename, 'wb') as f:
f.write(response.content)
print('已成功下载图片:' + filename)
```
您可以将 `url` 替换为目标图片的链接。在上述示例中,我们使用了 Python 的 requests 库来发送 HTTP 请求,然后将响应的内容保存到本地文件中。请注意,您需要确保您的代码具有下载目标图片的合法性。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)