我正在尝试向网站发送 HTTP 请求并读取它返回的数据。我尝试的第一个网站成功运行。它返回了大约 4 个数据包,然后返回了一个 0 数据包,脚本捕获并终止了该数据包。
但是,试图加载 http://www.google.com/这样不行。相反,它返回大约 10 个相同长度的数据包,最后一个较小的数据包,然后继续超时。发生这种情况是否正常?这是否完全取决于主机使用的服务器?
如果有人可以推荐一种替代方法来读取 socket.recv() ,该方法会考虑到并不总是发送最终的空数据包,我们将不胜感激。谢谢。
try:
data = s.recv(4096)
while True:
more = s.recv(4096)
print len(more)
if not more:
break
else:
data += more
except socket.timeout:
errMsg = "Connection timed-out while connecting to %s. Request headers were as follows: %s", (parsedUrl.netloc, rHeader.headerContent)
self.logger.exception(errMsg)
raise Exception
最佳答案
对于 HTTP,使用 requests而不是自己编写。
> ipython
In [1]: import requests
In [2]: r = requests.get('http://www.google.com')
In [3]: r.status_code
Out[3]: 200
In [4]: r.text[:80]
Out[4]: u'<!doctype html><html itemscope="itemscope" itemtype="http://schema.org/WebPage">'
In [5]: len(r.text)
Out[5]: 10969
关于python - 如何读取 Python socket recv,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12110903/