我有一个在安装了 LXDE 和 Firefox 的 VPS 上运行的 Ubuntu 服务器。我也使用这个命令启动了 Selenium 服务器:
java -jar selenium-server-standalone-2.33.0.jar
它现在正在运行并在 localhost 端口 4444 上侦听。要通过 PHP 连接到 selenium 服务器,我使用这个简单的脚本:
$url = "http://www.amazon.com";
$dc = array("browserName" => "firefox",
"version" => "",
"platform" => "ANY",
"javascriptEnabled" => True);
// To get the session id
$session_id = get_id($dc);
// Open 'amazon.com'
$new_map = "/session/".$session_id."/url";
$result = curl_transfer('POST', array('url' => $url), $new_map);
// Wait until the page completely been loaded
$new_map = "/session".$session_id."/timeouts/implicit_wait";
curl_transfer('POST', array('ms' => 7000), $new_map);
// Find an element, here is the Brazil link at the bottom of the page
$new_map = "/session/".$session_id."/element";
$t = curl_transfer('POST', array('using' => 'link text', 'value' => 'Brazil'), $new_map);
print_r($t);
function curl_transfer ($method, $params, $map){
$path = 'http://localhost:4444/wd/hub'.$map;
$c = curl_init($path);
if ($method === 'POST') {
$encoded_params = json_encode($params);
curl_setopt($c, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($c, CURLINFO_HEADER_OUT, true);
curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
curl_setopt($c, CURLOPT_HEADER, true);
curl_setopt($c, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json;charset=UTF-8',
'Accept: application/json',
'Expect:'));
curl_setopt($c, CURLOPT_POST, 1);
curl_setopt($c, CURLOPT_POSTFIELDS, $encoded_params);
$raw_result = curl_exec($c);
// print_r(curl_getinfo($c));
return (string)$raw_result;
}
if ($method === 'GET') {
curl_setopt($c, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($c, CURLINFO_HEADER_OUT, true);
curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
curl_setopt($c, CURLOPT_HEADER, true);
$raw_result = curl_exec($c);
// print_r(curl_getinfo($c));
return (string)$raw_result;
}
}
function get_id ($dc){
$result = curl_transfer('POST', array('desiredCapabilities' => $dc), '/session');
$array_result = explode ("\r\n", $result);
$id = str_replace("Location: http://localhost:4444/wd/hub/session/", "", $array_result[6]);
return $id;
}
一切正常,会话正在启动并且 Firefox 被导航到 Amazon.com,但是每次我尝试找到一个元素时,我都会将其作为返回对象:
{"status":0,"sessionId":"3a0d5939-595e-40d6-88c8-fe6f22a165dd","value":{"ELEMENT":"0"},"state":null,"class":"org.openqa.selenium.remote.Response","hCode":15920450}
似乎根本没有找到该元素。这里有什么问题?任何想法?