Python爬取网页图片
时间: 2023-09-24 13:03:42 浏览: 42
你可以使用 Python 中的 requests 库和 BeautifulSoup 库来爬取网页图片。以下是一个简单的示例代码:
```python
import requests
from bs4 import BeautifulSoup
# 目标网页 URL
url = 'https://www.example.com'
# 发送 GET 请求并获取响应
response = requests.get(url)
# 解析 HTML 页面
soup = BeautifulSoup(response.text, 'html.parser')
# 找到所有的图片标签
img_tags = soup.find_all('img')
# 遍历图片标签并下载图片
for img_tag in img_tags:
# 获取图片链接
img_url = img_tag['src']
# 发送 GET 请求并获取图片内容
img_response = requests.get(img_url)
# 将图片内容写入本地文件
with open('image.jpg', 'wb') as f:
f.write(img_response.content)
```
这段代码会将目标网页中的所有图片下载下来并保存在本地文件中。你可以根据实际需求对代码进行修改和优化。
相关问题
python爬取网页图片保存
可以使用Python中的requests和BeautifulSoup库来爬取网页图片并保存。
首先,使用requests库发送一个GET请求获取网页内容,然后使用BeautifulSoup库解析网页内容,找到所有需要下载的图片的URL。
接下来,使用requests库发送一个GET请求下载图片,并将其保存到本地。
以下是一个简单的示例代码:
```python
import requests
from bs4 import BeautifulSoup
url = 'https://www.example.com' # 网页链接
response = requests.get(url) # 发送GET请求获取网页内容
soup = BeautifulSoup(response.text, 'html.parser') # 解析网页内容
# 找到所有需要下载的图片的URL
image_urls = []
for img in soup.find_all('img'):
image_urls.append(img.get('src'))
# 下载并保存图片
for url in image_urls:
response = requests.get(url)
with open(url.split('/')[-1], 'wb') as f:
f.write(response.content)
```
在上面的示例代码中,将下载的图片保存在当前工作目录下,并以图片的文件名作为文件名保存。
python爬取网页图片代码
以下是一个简单的 Python 代码示例,可以爬取指定网页中的图片并保存到本地:
```python
import requests
from bs4 import BeautifulSoup
import os
# 指定要爬取的网页链接
url = "http://example.com"
# 发送 HTTP GET 请求
response = requests.get(url)
# 使用 BeautifulSoup 解析 HTML 内容
soup = BeautifulSoup(response.content, 'html.parser')
# 创建保存图片的文件夹
if not os.path.exists("images"):
os.makedirs("images")
# 遍历所有 <img> 标签,获取图片链接并下载保存到本地
for img in soup.find_all('img'):
img_url = img.get('src')
if img_url.startswith('http'):
response = requests.get(img_url)
with open("images/" + img_url.split("/")[-1], "wb") as f:
f.write(response.content)
print("下载图片:", img_url)
```
这段代码使用了 requests 库发送 HTTP GET 请求,使用 BeautifulSoup 库解析 HTML 内容,遍历所有的 img 标签,获取图片链接并下载保存到本地。请注意,此代码仅供参考,具体实现可能因网页结构和图片链接格式而有所不同。
相关推荐
![7z](https://img-home.csdnimg.cn/images/20210720083312.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.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)
![md](https://img-home.csdnimg.cn/images/20210720083646.png)