爬虫下载网页的全部文件
时间: 2024-05-05 14:20:12 浏览: 23
爬虫下载网页的全部文件可以通过以下步骤实现:
1. 使用Python中的requests库发送HTTP请求,获取网页的HTML源代码。
2. 解析HTML源代码,获取网页中的所有链接,包括图片、CSS、JS等资源链接。
3. 遍历所有链接,逐个发送HTTP请求,获取对应的资源文件。
4. 将资源文件保存到本地。
示例代码如下:
```python
import requests
from bs4 import BeautifulSoup
import os
# 定义要下载的网页链接
url = 'https://example.com'
# 发送HTTP请求,获取网页HTML源代码
response = requests.get(url)
html = response.text
# 解析HTML源代码,获取网页中的所有链接
soup = BeautifulSoup(html, 'html.parser')
links = soup.find_all('a')
images = soup.find_all('img')
scripts = soup.find_all('script')
styles = soup.find_all('link')
# 遍历所有链接,下载对应的资源文件
for link in links + images + scripts + styles:
href = link.get('href') or link.get('src')
if href:
# 如果链接是相对路径,则拼接成绝对路径
if not href.startswith('http'):
href = url + href
# 发送HTTP请求,获取资源文件
response = requests.get(href)
# 获取文件名
filename = os.path.basename(href)
# 保存文件到本地
with open(filename, 'wb') as f:
f.write(response.content)
```
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)