使用CURL授权后用HTML DOM解析页面


Parse page with HTML DOM after authorization with CURL

我正在寻找一个解决方案,如何使用CURL授权后使用简单的HTML DOM解析器解析页面。

现在我有两个工作部分的代码:CURL授权和简单的HTML DOM解析器

1)授权使用CURL

$data = array();
$data['name'] = 'name';
$data['pass'] = 'pass';
$data['loginbtnUp'] = '1';
$data['submit_flag'] = '1';
$data['rand'] = microtime(true);
$data['formSubmitted']=1;
$post_str = '';
foreach($data as $key=>$val) {
    $post_str .= $key.'='.urlencode($val).'&';
}
$post_str = substr($post_str, 0, -1);
$cookie_file = "cookie.txt";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://login.page.com/' );
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_str);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file);
curl_setopt($ch, CURLOPT_AUTOREFERER, 1); 
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); 
$response = curl_exec($ch );
echo $response;
curl_close($ch);

2)和简单HTML DOM解析器

include('simple_html_dom.php');
$context = stream_context_create(array('http' => array(
  'header' => 'User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.60 Safari/537.17'
)));
$html = str_get_html( file_get_contents('http://page.com/user1', false, $context) );
foreach($html->find('img[width="200"]') as $e)
    echo $e->src . '<br>';

我的问题是如何组合那些部分代码来解析只有授权用户才能访问的页面。我只需要一次登录,然后解析不同的页面,这是可供授权用户

您已经使用CURL登录了,这很好,但是CURL现在将您的cookie保存在您的CURLOPT_COOKIEJAR文件中。

为了让网站继续为你提供受保护的内容,你需要在登录后继续提供它给你的会话cookie。

因此,你对密码保护页面的额外请求应该像你的登录过程一样使用CURL(除了,显然,你不需要POST,你只需要GET):

$ch = curl_init('https://login.page.com/protectedcontent');
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file);
curl_setopt($ch, CURLOPT_AUTOREFERER, true); 
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); 
$response = curl_exec($ch);
curl_close($ch);
$dom = str_get_html($response);