python - 无法使用套接字获取所需内容

标签 python python-3.x sockets web-scraping

我正在尝试从 here 获取可见内容使用 socket 但不幸的是,我在执行脚本时遇到错误。由于我对使用 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.

最佳答案

通过将 \r\n\r\n 添加到请求命令的末尾,而不是原来的 \n\n,我能够获得所需的结果>:

import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((socket.gethostbyname('data.pr4e.org'), 80))
s.sendall("GET http://data.pr4e.org/romeo.txt HTTP/1.0\r\n\r\n".encode())
print(s.recv(1024))

输出:

...
Content-Type: text/plain\r\n\r\nBut soft what light through yonder window breaks\nIt is the east and Juliet is the sun\nArise fair sun and kill the envious moon\nWho is already sick and pale with grief\n'

关于python - 无法使用套接字获取所需内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53026133/

相关文章:

python - 将 openpyxl 数据传递给 pandas

python - 如何将 Pandas 中的嵌套 json 分解为行?

python - 在django中实现静态文件的错误

php - Python ajax php解析结果与屏幕上的结果不同?

python-3.x - 下拉菜单更改顺序并每次删除一个选项 - Python

python - 属性错误 : type object 'socket' has no attribute 'socket'

linux - 虚拟 IP 配置不起作用,我仍然收到地址已在使用错误

python-3.x - Tensorflow 2.0 无效参数错误 : assertion failed: [Condition x == y did not hold element-wise:]

python - 比较两个非匹配列表并找出具有最大匹配元素的行

安卓网络