通过编写Python爬虫程序,从实训2.6的壁纸网站上(https://www.netbian.com/weimei/index.htm)爬取并下载页面壁纸图片。 完整代码
时间: 2024-11-06 12:36:52 浏览: 58
在Python中编写爬虫程序来抓取网页内容并下载壁纸图片通常需要使用一些库,如requests用于发送HTTP请求获取HTML源码,BeautifulSoup或lxml用于解析HTML,以及os和io用于处理文件操作。下面是一个简单的示例,展示如何使用这些库来完成这个任务。注意,实际运行时可能需要处理反爬机制、动态加载的内容等问题。
```python
import requests
from bs4 import BeautifulSoup
import os
# 目标URL
url = "https://www.netbian.com/weimei/index.htm"
# 发送GET请求
response = requests.get(url)
html_content = response.text
# 解析HTML内容
soup = BeautifulSoup(html_content, 'lxml')
images = soup.find_all('img') # 假设壁纸图片标签通常是`<img>`
# 创建保存图片的目录(如果不存在)
if not os.path.exists("wallpapers"):
os.makedirs("wallpapers")
for image in images:
img_url = image['src'] # 获取图片链接
response_img = requests.get(img_url)
# 检查是否成功获取到图片
if response_img.status_code == 200:
file_name = os.path.join("wallpapers", img_url.split("/")[-1]) # 获取图片文件名
with open(file_name, 'wb') as f:
f.write(response_img.content)
print(f"已下载图片: {file_name}")
else:
print(f"无法下载图片 {img_url}, HTTP状态码: {response_img.status_code}")
阅读全文
相关推荐


















