用python写爬取图片的代码
时间: 2023-09-16 09:06:35 浏览: 126
### 回答1:
以下是一个使用 Python 和库 `requests` 和 `BeautifulSoup` 爬取图片的简单示例代码:
```python
import requests
from bs4 import BeautifulSoup
url = 'https://example.com/images'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
images = soup.find_all('img')
for image in images:
img_url = image['src']
response = requests.get(img_url)
open(img_url.split('/')[-1], 'wb').write(response.content)
```
这段代码首先通过 `requests.get(url)` 向网站发送请求,获取网页的 HTML 内容。然后使用 `BeautifulSoup` 解析 HTML,并使用 `soup.find_all('img')` 查找所有图片标签。最后,循环遍历所有图片标签,获取图片的 URL,并使用 `requests.get(img_url)` 再次发送请求获取图片内容,最后使用 `open(img_url.split('/')[-1], 'wb').write(response.content)` 将图片保存到本地。
注意:这只是一个简单的示例,在实际使用中,还需要考虑网络连接错误、重定向、网站反爬虫等问题。
### 回答2:
要使用Python编写一个爬取图片的代码,可以使用第三方库Requests和BeautifulSoup来实现。
首先,需要安装这两个库,可以使用pip命令来安装:
```python
pip install requests
pip install beautifulsoup4
```
然后,导入库:
```python
import requests
from bs4 import BeautifulSoup
```
接下来,定义一个函数来下载图片:
```python
def download_image(url, filename):
response = requests.get(url, stream=True)
with open(filename, 'wb') as file:
for chunk in response.iter_content(chunk_size=1024):
if chunk:
file.write(chunk)
```
接着,编写爬取图片的主程序:
```python
def main():
url = "https://example.com" # 替换为你要爬取图片的网址
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
images = soup.find_all('img')
for image in images:
image_url = image['src']
image_filename = image_url.split('/')[-1]
download_image(image_url, image_filename)
print(f"下载图片:{image_filename}")
if __name__ == '__main__':
main()
```
以上代码通过请求网址获取网页内容,并使用BeautifulSoup库解析网页。然后,通过find_all方法找到所有的img标签,并获取每张图片的url。最后,调用download_image函数下载图片并保存到本地。
请注意,上述代码只是一个基本示例,实际爬取图片时可能需要处理更多的异常情况和网站的反爬机制。