Perl의 www :: 기계화와 동등한 PHP가 있습니까?
-
11-07-2019 - |
문제
Perl과 유사한 기능을 가진 라이브러리를 찾고 있습니다. www :: 기계화, 그러나 php. 기본적으로 간단한 구문으로 http get and post 요청을 제출 한 다음 결과 페이지를 구문 분석하고 페이지의 모든 링크와 함께 모든 양식과 해당 필드를 간단한 형식으로 반환 할 수 있어야합니다.
나는 컬에 대해 알고 있지만 약간 너무 베어 본이이고 구문은 꽤 못 생겼다 ( curl_foo($curl_handle, ...)
진술
설명:
나는 지금까지 답보다 더 높은 수준의 것을 원한다. 예를 들어, Perl에서는 다음과 같은 작업을 수행 할 수 있습니다.
# navigate to the main page
$mech->get( 'http://www.somesite.com/' );
# follow a link that contains the text 'download this'
$mech->follow_link( text_regex => qr/download this/i );
# submit a POST form, to log into the site
$mech->submit_form(
with_fields => {
username => 'mungo',
password => 'lost-and-alone',
}
);
# save the results as a file
$mech->save_content('somefile.zip');
http_client 또는 wget 또는 curl을 사용하여 동일한 작업을 수행하려면 많은 작업이 될 것입니다. 링크를 찾으려면 페이지를 수동으로 구문 분석하고, URL 양식을 찾고, 모든 숨겨진 필드를 추출하는 등을 사용해야합니다. PHP 솔루션을 요구하는 이유는 PERL에 대한 경험이없고 많은 작업으로 필요한 것을 구축 할 수 있지만 PHP에서 위를 할 수 있다면 훨씬 빠릅니다.
해결책
단순한 ScriptableBrowser 테스트 프레임 워크에서 독립적으로 사용할 수 있습니다. 수많은 자동화 작업에 사용했습니다.
다른 팁
나는 오래된 게시물이지만 이것에 대답해야한다고 느낀다 ... 나는 PHP Curl과 함께 일하고 있었고 www : mechanize와 비슷한 곳과 비교할 수있는 곳은 좋지 않다 (나는 생각한다. Ruby Language 구현과 함께 갈 것입니다) .. Curl은 무엇이든 자동하기 위해 너무 많은 "Grunt Work"가 필요하기 때문에 구식입니다. 가장 간단한 스크립트 가능한 브라우저는 나에게 유망한 것으로 보였지만 테스트 할 때 대부분의 웹에서 작동하지 않습니다. 내가 시도해 보는 형태 ... 솔직히 말해서, 나는이 범주의 스크래핑, 웹 자동화에 PHP가 부족하다고 생각합니다. 그래서 다른 언어를 보는 것이 가장 좋습니다. 미래에 다른 사람을 구할 것입니다.
지금은 2016 년입니다 밍크. 심지어 Headless Pure-PHP "Browser"(JavaScript 없음), Selenium (Firefox 또는 Chrome과 같은 브라우저가 필요함)을 통해 NPM의 Headless "Browser.js"와 함께 JavaScript를 지원합니다.
배 라이브러리를 살펴보십시오. 다른 모든 것이 실패하면 컬에 대한 객체 래퍼를 만듭니다.
당신은 다음과 같이 단순한 것을 할 수 있습니다 :
class curl {
private $resource;
public function __construct($url) {
$this->resource = curl_init($url);
}
public function __call($function, array $params) {
array_unshift($params, $this->resource);
return call_user_func_array("curl_$function", $params);
}
}
다음 중 하나를 시도하십시오.
(예, Zendframework 코드이지만 필요한 Libs를로드하기 때문에 클래스가 느리게 만들지는 않습니다.)
Snoopy를 살펴보세요 :http://sourceforge.net/projects/snoopy/
Curl은 간단한 요청을받는 방법입니다. 크로스 플랫폼을 실행하고 PHP 확장 기능이 있으며 널리 채택되고 테스트됩니다.
Curlhandler :: get ($ URL, $ data) ||로 전화를 걸어 URL에 다양한 데이터 (파일 포함)를 게시 할 수있는 멋진 클래스를 만들었습니다. Curlhandler :: Post ($ URL, $ data). 선택적 HTTP 사용자 인증 옵션도 있습니다 :)
/**
* CURLHandler handles simple HTTP GETs and POSTs via Curl
*
* @package Pork
* @author SchizoDuckie
* @copyright SchizoDuckie 2008
* @version 1.0
* @access public
*/
class CURLHandler
{
/**
* CURLHandler::Get()
*
* Executes a standard GET request via Curl.
* Static function, so that you can use: CurlHandler::Get('http://www.google.com');
*
* @param string $url url to get
* @return string HTML output
*/
public static function Get($url)
{
return self::doRequest('GET', $url);
}
/**
* CURLHandler::Post()
*
* Executes a standard POST request via Curl.
* Static function, so you can use CurlHandler::Post('http://www.google.com', array('q'=>'StackOverFlow'));
* If you want to send a File via post (to e.g. PHP's $_FILES), prefix the value of an item with an @ !
* @param string $url url to post data to
* @param Array $vars Array with key=>value pairs to post.
* @return string HTML output
*/
public static function Post($url, $vars, $auth = false)
{
return self::doRequest('POST', $url, $vars, $auth);
}
/**
* CURLHandler::doRequest()
* This is what actually does the request
* <pre>
* - Create Curl handle with curl_init
* - Set options like CURLOPT_URL, CURLOPT_RETURNTRANSFER and CURLOPT_HEADER
* - Set eventual optional options (like CURLOPT_POST and CURLOPT_POSTFIELDS)
* - Call curl_exec on the interface
* - Close the connection
* - Return the result or throw an exception.
* </pre>
* @param mixed $method Request Method (Get/ Post)
* @param mixed $url URI to get or post to
* @param mixed $vars Array of variables (only mandatory in POST requests)
* @return string HTML output
*/
public static function doRequest($method, $url, $vars=array(), $auth = false)
{
$curlInterface = curl_init();
curl_setopt_array ($curlInterface, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_FOLLOWLOCATION =>1,
CURLOPT_HEADER => 0));
if (strtoupper($method) == 'POST')
{
curl_setopt_array($curlInterface, array(
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => http_build_query($vars))
);
}
if($auth !== false)
{
curl_setopt($curlInterface, CURLOPT_USERPWD, $auth['username'] . ":" . $auth['password']);
}
$result = curl_exec ($curlInterface);
curl_close ($curlInterface);
if($result === NULL)
{
throw new Exception('Curl Request Error: '.curl_errno($curlInterface) . " - " . curl_error($curlInterface));
}
else
{
return($result);
}
}
}
?>
편집] 지금만 설명을 읽으십시오 ... 아마도 물건을 자동화하는 위에서 언급 한 도구 중 하나와 함께 가고 싶을 것입니다. Clientside Firefox Extension을 사용하기로 결정할 수도 있습니다. 치킨 풋 더 많은 유연성을 위해. 향후 검색을 위해 여기에 예제 수업을 남겨 두겠습니다.
프로젝트에서 CakePHP를 사용하거나 관련 라이브러리를 추출하려는 경향이있는 경우 컬 래퍼 httpsocket을 사용할 수 있습니다. 설명하는 간단한 페이지 가져 오기 구문이 있습니다.
# This is the sugar for importing the library within CakePHP
App::import('Core', 'HttpSocket');
$HttpSocket = new HttpSocket();
$result = $HttpSocket->post($login_url,
array(
"username" => "username",
"password" => "password"
)
);
... 응답 페이지를 구문 분석하는 방법은 없지만. 이를 위해 나는 simplehtmldom을 사용할 것입니다. http://net.tutsplus.com/tutorials/php/html-parsing-and-screen-scraping-with-the-simple-dom-library/ jQuery와 같은 구문을 가진 것으로 묘사합니다.
결론은 PHP에 Perl/Ruby가 가지고있는 멋진 스크래핑/자동화 라이브러리가 없다는 것입니다.
*nix 시스템에있는 경우 wget과 함께 shell_exec ()를 사용할 수 있습니다. 이는 많은 옵션이 있습니다.