在Python中获取网页源代码通常使用 `requests` 库,它是一个第三方HTTP库,可以方便地发送HTTP请求并获取网页内容。以下是使用 `requests` 库获取网页源代码的基本步骤:
1. 安装 `requests` 库:
pip install requests
2. 导入 `requests` 库并发送HTTP GET请求:
import requests
url = 'https://example.com' 替换为你想获取源代码的网址
response = requests.get(url)
3. 获取网页内容并打印:
html_content = response.text
print(html_content)
4. 如果需要,可以指定编码格式,通常为 `utf-8`:
html_content = response.text
print(html_content.encode('utf-8').decode('utf-8'))
5. 如果需要保存网页内容到文件,可以使用以下代码:
with open('output.html', 'w', encoding='utf-8') as file:
file.write(html_content)
以上步骤可以帮助你获取网页源代码。如果你需要解析HTML内容,可以使用 `BeautifulSoup` 库,它是一个用于解析HTML和XML文档的库。