Python 请求网页:处理缺少 http 或 https 前缀的连接
当连接缺少了http://或https://时,可以通过判断连接字符串的开头来补充缺失的部分。如果连接字符串以http://或https://开头,则直接发送请求;否则,在连接字符串前面加上http://再发送请求。\n\n以下是一个示例代码:\n\npython\nimport requests\n\ndef request_webpage(url):\n if url.startswith('http://') or url.startswith('https://'):\n response = requests.get(url)\n else:\n response = requests.get('http://' + url)\n \n if response.status_code == 200:\n # 请求成功\n print(response.text)\n else:\n # 请求失败\n print('请求失败')\n\n# 示例使用\nrequest_webpage('example.com')\n\n\n在示例中,首先判断连接字符串是否以http://或https://开头,如果是,则直接发送请求;否则,在连接字符串前面加上http://再发送请求。最后,根据响应的状态码判断请求是否成功,并根据需要进行处理。
原文地址: https://www.cveoy.top/t/topic/p0Zw 著作权归作者所有。请勿转载和采集!