如何实现HTTP/HTTPS检测中Bad结果单行覆盖、Good结果换行输出?
HTTP/HTTPS检测输出优化方案
问题说明
正在做HTTP/HTTPS检测,规则为:若站点从HTTP请求重定向到HTTPS,则判定为使用HTTPS,标记为Bad;合规结果为HTTP,标记为Good。需要实现:
- Good结果换行保留,每条占一行
- Bad结果始终覆盖同一行的旧Bad结果,不会被Good结果挤开
原代码存在逻辑错误,且输出控制不符合预期:
import requests, re r = requests.get(f'http://{uri}') resp = r.history resp = re.findall('https:\/\/',r) # 此处错误,无法直接将响应对象传入re.findall if not resp: print('Good, its not https for ' + uri) else: print('Bad, its https')
修改输出逻辑后仍达不到目标效果:
if not resp: print('Good, its not https for ' + uri + '\n') print() else: print('Bad, its https for' + uri, end='')
当前错误输出:
Bad, its https for www.microsoft.com Good, its not https for zendesk.line.me Bad, its https for www.google.com Good, its not https for note.microsoft.com
期望输出:
Good, its not https for zendesk.line.me Good, its not https for note.microsoft.com Bad, its https for www.google.com ## 覆盖之前的www.microsoft.com
解决方案
1. 修正检测逻辑
不能用正则匹配响应对象,应通过检查重定向历史或最终响应URL,判断站点是否跳转到HTTPS。
2. 实现输出覆盖
使用\r(回车符)回到当前行开头,结合sys.stdout.flush()强制刷新输出缓冲区,确保Bad内容能立即覆盖上一条Bad记录,同时Good记录正常换行。
修正后的完整代码:
import requests import sys def check_http_https(uri): try: # 发送HTTP请求,允许自动跟随重定向 r = requests.get(f'http://{uri}', allow_redirects=True, timeout=5) # 判断是否存在HTTPS重定向:检查重定向历史或最终响应URL is_https = any('https://' in redirect.url for redirect in r.history) or r.url.startswith('https://') if not is_https: # Good结果正常换行,永久保留 print(f'Good, its not https for {uri}') else: # 用\r回到行首覆盖旧Bad内容,end=''避免自动换行 sys.stdout.write(f'\rBad, its https for {uri}') sys.stdout.flush() except requests.exceptions.RequestException as e: # 处理请求异常(超时、无法连接等) print(f'Error accessing {uri}: {str(e)}') # 示例遍历wordlist wordlist = ['www.microsoft.com', 'zendesk.line.me', 'www.google.com', 'note.microsoft.com'] for uri in wordlist: check_http_https(uri) # 最后换行,避免最后一条Bad内容被命令行提示符覆盖 print()
关键说明
- 检测逻辑修正:通过
r.history检查重定向过程中的URL,或直接判断最终响应URL的协议,准确识别HTTPS重定向。 - 输出控制:
- Good结果用
print()正常输出,自动换行后不会被覆盖。 - Bad结果用
sys.stdout.write()结合\r移动光标到行首,覆盖之前的Bad内容;sys.stdout.flush()确保输出立即生效,避免缓冲区延迟。 - 遍历结束后添加
print(),防止最后一条Bad内容被命令行提示符覆盖。
- Good结果用
内容的提问来源于stack exchange,提问作者user19219732
相关产品推荐
相关产品推荐

