我正在尝试向POST
服务器发送原始chromedriver
请求。
以下是我尝试发起new session
:
import socket
s = socket.socket(
socket.AF_INET, socket.SOCK_STREAM)
s.connect(("127.0.0.1", 9515))
s.send(b'POST /session HTTP/1.1\r\nContent-Type:application/json\r\n{"capabilities": {}, "desiredCapabilities": {}}\r\n\r\n')
response = s.recv(4096)
print(response)
输出:
b'HTTP/1.1 200 OK\r\nContent-Length:270\r\nContent-Type:application/json; charset=utf-8\r\nConnection:close\r\n\r\n{"sessionId":"b26166c2aac022566917db20260500bb","status":33,"value":{"message":"session not created exception: Missing or invalid capabilities\\n (Driver info: chromedriver=2.31.488763 (092de99f48a300323ecf8c2a4e2e7cab51de5ba8),platform=Linux 4.4.0-91-generic x86_64)"}}'
错误摘要:我发送的json
对象未正确解析
当我使用相同的json
对象但是通过requests
库发送它时,一切正常:
import requests
params = {
'capabilities': {},
'desiredCapabilities': {}
}
headers = {'Content-type': 'application/json'}
URL = "http://127.0.0.1:9515"
r = requests.post(URL + "/session", json=params)
print("Status: " + str(r.status_code))
print("Body: " + str(r.content))
输出:
Status: 200
Body: b'{"sessionId":"e03189a25d099125a541f3044cb0ee42","status":0,"value":{"acceptSslCerts":true,"applicationCacheEnabled":false,"browserConnectionEnabled":false,"browserName":"chrome","chrome":{"chromedriverVersion":"2.31.488763 (092de99f48a300323ecf8c2a4e2e7cab51de5ba8)","userDataDir":"/tmp/.org.chromium.Chromium.LBeQkw"},"cssSelectorsEnabled":true,"databaseEnabled":false,"handlesAlerts":true,"hasTouchScreen":false,"javascriptEnabled":true,"locationContextEnabled":true,"mobileEmulationEnabled":false,"nativeEvents":true,"networkConnectionEnabled":false,"pageLoadStrategy":"normal","platform":"Linux","rotatable":false,"setWindowRect":true,"takesHeapSnapshot":true,"takesScreenshot":true,"unexpectedAlertBehaviour":"","version":"60.0.3112.90","webStorageEnabled":true}}'
输出摘要:json
成功解析chromedriver
对象,并创建new session
您是否知道为什么使用POST
发送原始socket
请求无法正常工作?
答案 0 :(得分:5)
您的HTTP请求有几个问题:
\r\n\r\n
Content-Length
字段,否则远程主机不知道您的身体何时完整。Host
字段。 (由于您收到200
第一次请求,服务器可能不会坚持。)我已经通过使用:
让您的示例(使用apache webserver)工作s.send(b'POST /session HTTP/1.1\r\nHost: 127.0.0.1:9515\r\nContent-Type: application/json\r\nContent-Length: 47\r\n\r\n{"capabilities": {}, "desiredCapabilities": {}}')
为了在视觉上更清晰,有效的HTTP
请求看起来像
POST /session HTTP/1.1
Host: 127.0.0.1:9515
Content-Type: application/json
Content-Length: 47
{"capabilities": {}, "desiredCapabilities": {}}