【发布时间】:2018-10-27 20:45:35
【问题描述】:
我正在尝试使用 socket 从 here 获取可见内容,但不幸的是,我在执行脚本时遇到了错误。由于我对使用 socket 进行编码非常陌生,所以我不明白我哪里出错了。
我的代码:
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host_ip = socket.gethostbyname('data.pr4e.org')
s.connect((host_ip,80))
cmd = "GET http://data.pr4e.org/romeo.txt HTTP/1.0\n\n".encode()
s.send(cmd)
while True:
data = s.recv(1024)
if (len(data) <1 ):
break
print(data.decode())
s.close()
我得到的错误:
400 Bad Request
Your browser sent a request that this server could not understand.
【问题讨论】:
-
此错误来自服务器。您的脚本正在正确读取响应。
-
还不如只使用请求库....
-
Here 是一个相关的 SO 问题。
标签: python python-3.x sockets web-scraping