import requests
# 使用requests库来获取网页数据
def get_webpage_data(url):
try:
# 发送HTTP GET请求
response = requests.get(url)
# 检查请求是否成功
if response.status_code == 200:
# 返回网页内容
return response.text
else:
return f"Error: Unable to retrieve data, status code {response.status_code}"
except Exception as e:
return f"Error: {str(e)}"
# 示例URL
url = "https://www.example.com"
# 获取网页数据
webpage_content = get_webpage_data(url)
print(webpage_content)
requests
库来发送HTTP请求并获取网页内容。get_webpage_data(url)
函数接收一个URL作为参数,并尝试获取该URL的网页内容。requests.get(url)
发送GET请求。try-except
块捕获可能发生的异常,并返回相应的错误信息。希望这段代码和解释对你有帮助!
上一篇:python 数组添加
下一篇:遍历python
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站