关键技术
- Requests库:一个简单易用的HTTP库,用于发送网络请求。
- BeautifulSoup库:用于解析HTML和XML文档,从中提取所需数据。
- OS模块:提供了多种操作文件和目录的功能。
爬虫步骤
- 发送HTTP请求: 使用
requests.get函数,携带伪装的User-Agent头部,获取目标URL的网页源码。这是因为一些网站会根据请求的User-Agent来判断是否是爬虫访问。 - 解析HTML文档: 通过
BeautifulSoup(html, 'html.parser')解析获取到的HTML源码,准备提取图片URL。 - 图片URL提取: 使用
soup.find_all('img')获取所有图片标签,然后提取每个标签的图片URL。为处理可能的相对URL,我们会检查并补全URL。 - 创建目录并下载图片: 用
os.makedirs('bilibili_images', exist_ok=True)创建一个用于存放下载图片的目录。遍历所有图片URL,用requests.get下载,并保存到指定目录。
import requests
import os
from bs4 import BeautifulSoup
def download_images(url):
# 发送HTTP请求获取网页源代码
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.82 Safari/537.36'
}
response = requests.get(url, headers=headers)
html = response.text
# 使用BeautifulSoup解析HTML内容
soup = BeautifulSoup(html, 'html.parser')
# 创建一个目录用于保存图片
os.makedirs('bilibili_images', exist_ok=True)
# 找到所有图片的标签
img_tags = soup.find_all('img')
# 遍历所有图片标签,下载图片
for img in img_tags:
img_url = img.get('data-src') or img.get('src')
if img_url.startswith('//'):
img_url = 'https:' + img_url
# 下载图片
response = requests.get(img_url)
# 提取图片文件名
img_file = img_url.split('/')[-1]
# 将图片保存到指定目录下
with open('bilibili_images/' + img_file, 'wb') as f:
f.write(response.content)
print(f"Downloaded: {img_file}")
# 要爬取的文章URL
article_url = 'https://www.bilibili.com/read/cv18302467/'
download_images(article_url)