python下载HTML
时间: 2024-05-31 16:06:26 浏览: 153
如果您想下载网页的 HTML,您可以使用 Python 自带的 urllib 库或者 requests 库进行下载。其中 urllib 库是 Python 内置的标准库,而 requests 库则需要通过 pip 安装。以下是两种库的使用方法:
使用 urllib 库下载 HTML:
```python
import urllib.request
response = urllib.request.urlopen('http://www.example.com')
html = response.read()
print(html)
```
使用 requests 库下载 HTML:
```python
import requests
response = requests.get('http://www.example.com')
html = response.content
print(html)
```
上述代码可以将网页的 HTML 代码打印出来。如果您想将 HTML 保存到本地文件中,可以使用以下代码:
```python
import urllib.request
response = urllib.request.urlopen('http://www.example.com')
html = response.read()
with open('example.html', 'wb') as f:
f.write(html)
```
以上代码将 HTML 内容保存到 example.html 文件中。
阅读全文
相关推荐















