ホームページ  >  記事  >  バックエンド開発  >  Cookie を使用して Web サイトにアクセスし、ソース コードをダウンロードしてファイルに保存する方法を尋ねます。

Cookie を使用して Web サイトにアクセスし、ソース コードをダウンロードしてファイルに保存する方法を尋ねます。

WBOY
WBOYオリジナル
2016-06-23 14:05:501026ブラウズ

一生懸命検索しましたが、結果が見つかりませんでした。
Cookie のある Web サイトにアクセスして、ソース コードを読み、ファイルに保存するか、出力していただけますか。初心者の方は、よろしくお願いします。

自分で書きましたが、これは元のページの効果しか出力できず、ソースコードは見ることができません。 。 。ループを追加しましたが、機能しません。 。

<?php $url = 'http://weibo.com/***/follow'; $data = array ('foo' => 'bar'); $data = http_build_query($data); $opts = array ( 'http' => array (    'method' => 'GET',    'header'=> "Content-type: text/html" .                      "Content-Length: " . strlen($data) . "\r\n" . "cookie:***\r\n",'content' => $data ) ); $context = stream_context_create($opts); $html = file_get_contents($url,'',$context); //var_dump($html);$lines = file($html);//我估计这行可能写的不对//var_dump($lines);foreach($lines as $key => $value){   echo "{$key}:".htmlspecialchars($value)."<br>\n";}?> 


ディスカッション (解決策) に返信

$html = file_get_contents($url,'',$context);
ファイルの内容は $html にありませんか?
echo $html;
見てみればわかります

返信してくれたモデレータのおかげで、echo $html を試してみましたが、ブラウザは私が望んでいたソース コード効果ではなく、ページ全体を更新しました。

<?php$url = "http://www.baidu.com/";$lines = file($url);foreach($lines as $key => $value){   echo "{$key}:".htmlspecialchars($value)."<br>\n";}?> 
と同じように

出力結果はすべてのソースコードであり、これはあなたが望むものです。私の説明が明確かどうかわかりません。

自分で $html をファイルに保存し、テキスト エディターで開いて見てください

$html 自分でファイルに保存して、テキスト エディターで開いて見てください
あなたが言及した方法はうまくいきました今試してみた後、インターネット上の他の人の例を参照して、file_get_contentsを直接実行しましたが、問題は文字化けです。 。 。

<?php $url = 'http://weibo.com/**/follow'; $data = array ('foo' => 'bar'); $data = http_build_query($data); $opts = array ( 'http' => array (    'method' => 'GET',    'header'=> "Content-type: text/html" .                      "Content-Length: " . strlen($data) . "\r\n" . "cookie:**\r\n",'content' => $data ) ); $context = stream_context_create($opts); $html = file_get_contents($url,'',$context); //$source = htmlspecialchars($html);//$code = preg_match(pattern, subject)echo htmlspecialchars($html);//var_dump($html);//$lines = file($url);//$lines = file_get_contents($url);//var_dump($lines);//$files = fopen("text.txt","w");//fwrite($files,$lines);/*foreach($html as $key => $value){   echo "{$key}:".htmlspecialchars($value)."<br>\n";}*///fclose($lines);?> 

文字化けの原因は、エンコーディングが統一されていないためです。ヘッダーで文字セットを設定してください。
header("content-type:text/html;charset=utf-8");

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。