请求。获取()卡在控制室

2024-04-25 21:08:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图使用requests发出一个简单的get请求

import requests

def main():
    content = requests.get("https://google.com")
    print(content.status_code)

if __name__ == "__main__":
    main()

我在Linux上运行这个,17.10版。 Python版本:2.7或3.6(两者都试过)。你知道吗

代码被困在运行中,它不会超时或发生任何事情。你知道吗

在我停止它之后,基于调用堆栈,它被困在:

File "/usr/lib/python2.7/socket.py", line 228, in meth return getattr(self._sock,name)(*args)

Tags: namehttpsimportcomgetifmainlinux
1条回答
网友
1楼 · 发布于 2024-04-25 21:08:50

我刚刚在Python控制台上运行了您的代码,它返回了200。我正在运行python3.6.7和ubuntu18.04。他说

可能是您的计算机无法连接到谷歌网站在很长一段时间内,您应该传递timeout参数和try except

使用以下代码:

import requests

def main():
    success = False
    while success==False:
        try:
            content = requests.get("https://google.com", timeout=5)
            success=True
        except:
            pass
    print(content.status_code)

if __name__ == "__main__":
    main()

如果您的网络连接出现暂时性问题,此代码段将保证正确的响应。他说

相关问题 更多 >