PHPを使用してWebページを変数に入れる方法
-
22-08-2019 - |
質問
Webからページをダウンロードしたいのですが、Firefoxのような単純なブラウザを使用しているときに行うことができますが、「file_get_contents」を使用すると、サーバーはコマンドを理解しているがそのようなダウンロードを許可しないことを拒否し、返信します。
じゃあ何をすればいいの?いくつかのスクリプト(Perl)で、ユーザーエージェントとCookieを作成して、スクリプトを実際のブラウザのようにする方法を見たと思います。
誰かがこれについて考えていますか、それがどのようにできるのか?
解決
カールを使用します。
<?php
// create curl resource
$ch = curl_init();
// set url
curl_setopt($ch, CURLOPT_URL, "example.com");
//return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// set the UA
curl_setopt($ch, CURLOPT_USERAGENT, 'My App (http://www.example.com/)');
// Alternatively, lie, and pretend to be a browser
// curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)');
// $output contains the output string
$output = curl_exec($ch);
// close curl resource to free up system resources
curl_close($ch);
?>
他のヒント
ええ、Curlはページコンテンツを取得するのにかなり良いです。私はそれを次のようなクラスで使用します domdocument と DomxPath コンテンツを使用可能なフォームに粉砕します。
function __construct($useragent,$url)
{
$this->useragent='Firefox (WindowsXP) - Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.8.1.6) Gecko/20070725 Firefox/2.0.0.'.$useragent;
$this->url=$url;
$ch = curl_init();
curl_setopt($ch, CURLOPT_USERAGENT, $useragent);
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_FAILONERROR, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_AUTOREFERER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
$html= curl_exec($ch);
$dom = new DOMDocument();
@$dom->loadHTML($html);
$this->xpath = new DOMXPath($dom);
}
...
public function displayResults($site)
$data=$this->path[0]->length;
for($i=0;$i<$data;$i++)
{
$delData=$this->path[0]->item($i);
//setting the href and title properties
$urlSite=$delData->getElementsByTagName('a')->item(0)->getAttribute('href');
$titleSite=$delData->getElementsByTagName('a')->item(0)->nodeValue;
//setting the saves and additoinal
$saves=$delData->getElementsByTagName('span')->item(0)->nodeValue;
if ($saves==NULL)
{
$saves=0;
}
//build the array
$this->newSiteBookmark[$i]['source']='delicious.com';
$this->newSiteBookmark[$i]['url']=$urlSite;
$this->newSiteBookmark[$i]['title']=$titleSite;
$this->newSiteBookmark[$i]['saves']=$saves;
}
後者は、からデータを削るクラスの一部です dealious.com しかし、あまり合法ではありません。
この答えは、あなたのコメントをリッチの答えに念頭に置いています。
このサイトは、おそらくHTTP参照者またはユーザーエージェント文字列を使用して実際のユーザーであるかどうかを確認しています。カールにこれらを設定してみてください:
//pretend you came from their site already
curl_setopt($ch, CURLOPT_REFERER, 'http://domainofthesite.com');
//pretend you are firefox 3.06 running on windows Vista
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.0.6) Gecko/2009011913 Firefox/3.0.6');
それを行う別の方法(他の人はより良い方法を指摘していますが)は、phpのfopen()関数を使用することです。
$handle = fopen("http://www.example.com/", "r");//open specified URL for reading
Curlが利用できない場合に特に便利です。
所属していません StackOverflow