爬虫下载附件和图片
时间: 2025-07-21 10:13:09 浏览: 0
### 如何使用爬虫抓取并下载网页上的附件与图片
#### 下载网页中的附件
为了高效、准确地爬取并保存网页中的附件(如 PDF、Excel 和 Word 文件),可以利用 Python 的 `requests` 库和 `BeautifulSoup` 来解析 HTML 页面,找到目标附件的链接,并将其下载到本地[^1]。
以下是具体的代码示例:
```python
import requests
from bs4 import BeautifulSoup
import os
def download_attachment(url, folder="attachments"):
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
# 创建存储附件的目标文件夹
if not os.path.exists(folder):
os.makedirs(folder)
attachments = []
for link in soup.find_all('a', href=True):
file_url = link['href']
if any(file_url.endswith(ext) for ext in ['.pdf', '.xls', '.xlsx', '.doc', '.docx']):
filename = os.path.join(folder, file_url.split('/')[-1])
with open(filename, 'wb') as f:
attachment_content = requests.get(file_url).content
f.write(attachment_content)
attachments.append(filename)
return attachments
# 调用函数
downloaded_files = download_attachment("http://example.com/page_with_attachments") # 替换为目标页面URL
print(f"已成功下载的附件列表: {downloaded_files}")
```
上述代码会遍历指定 URL 中的所有 `<a>` 标签,筛选出以 `.pdf`, `.xls`, `.xlsx`, `.doc`, 或 `.docx` 结尾的链接,并将它们作为附件下载至名为 `attachments` 的目录下。
---
#### 抓取网页中的图片
PHP 可用于实现简单的图片抓取功能。下面展示了一种基于 PHP 的解决方案,该方案能够从远程服务器获取图片并将之保存到本地磁盘[^2]。
##### PHP 实现示例
```php
<?php
class ImageDownloader {
public function saveImage($url, $savePath) {
try {
$imageData = file_get_contents($url);
if ($imageData === false) throw new Exception("无法读取图像数据");
$result = file_put_contents($savePath, $imageData);
if ($result !== false) echo "图片 {$url} 已成功保存为 {$savePath}\n";
else throw new Exception("写入失败");
} catch (Exception $e) {
echo "错误: " . $e->getMessage() . "\n";
}
}
public function batchDownloadImages($urlsArray, $basePath) {
foreach ($urlsArray as $index => $imageUrl) {
$extension = pathinfo($imageUrl, PATHINFO_EXTENSION);
$filename = "{$basePath}/image_{$index}.{$extension}";
$this->saveImage($imageUrl, $filename);
}
}
}
// 使用实例
$downloader = new ImageDownloader();
$imageUrls = [
"https://example.com/image1.jpg",
"https://example.com/image2.png"
];
$downloader->batchDownloadImages($imageUrls, "./images"); // 图片会被存放在当前路径下的 images/ 目录中
?>
```
此脚本定义了一个 `ImageDownloader` 类,其中包含了两个主要方法:一个是单张图片的下载 (`saveImage`);另一个则是批量处理多个图片地址 (`batchDownloadImages`)。它支持自动生成文件名以及扩展名匹配。
---
#### 综合考虑动态加载的内容
如果遇到的是 JavaScript 动态渲染出来的内容,则可能需要借助 Selenium 或 Playwright 等工具模拟浏览器行为来提取完整的 DOM 数据后再进行分析。例如,在某些情况下仅靠 Requests 获取不到全部资源时可采用这种方式[^3]。
另外针对分页情况也可以设计循环机制逐步访问每一页的数据源直至结束条件满足为止[^4]。
---
阅读全文
相关推荐

















