用python爬虫爬取抽烟图片
时间: 2023-09-05 11:02:36 浏览: 96
python爬虫爬取美女图片
使用Python编写爬虫程序来爬取抽烟图片是可行的。下面是一个基本的思路和代码示例:
1. 导入所需的模块:
```python
import requests
from bs4 import BeautifulSoup
import os
```
2. 设置目标网站的URL地址,发送请求并获取响应:
```python
url = "http://example.com/smoking-images" # 替换为你要爬取的网站地址
response = requests.get(url)
```
3. 解析响应内容,使用BeautifulSoup库来提取图片的URL地址:
```python
soup = BeautifulSoup(response.text, 'html.parser')
images = soup.find_all('img')
image_urls = [img['src'] for img in images]
```
4. 创建保存图片的文件夹:
```python
folder_name = "smoking_images" # 替换为你想要保存图片的文件夹名称
if not os.path.exists(folder_name):
os.makedirs(folder_name)
```
5. 下载图片并保存到创建的文件夹中:
```python
for url in image_urls:
response = requests.get(url)
file_name = url.split('/')[-1]
with open(os.path.join(folder_name, file_name), 'wb') as f:
f.write(response.content)
```
以上就是基本的代码示例,你可以根据实际情况进行修改和扩展。请注意,爬取图片时一定要遵守法律法规和网站的规定,不要违反相关规定。
阅读全文