结合CURL和SimpleHTMLDOM来抓取数据


Combine CURL and Simple HTML DOM for scraping data

我分配了一项任务,从一个受密码保护的网站上抓取数据,我是通过CURL完成的,但现在我想在CURL返回的html中获取链接,然后转到该链接并从那里抓取数据。我将CURL的响应传递到file_get_contents(),但没有工作。这是我的CURL代码。

$ckfile = tempnam("/tmp", "CURLCOOKIE");
$useragent = 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/533.2 (KHTML,    like Gecko) Chrome/5.0.342.3 Safari/533.2';
$username = "XXXXXX";
$password = "XXXXXX";

$f = fopen('log.txt', 'w'); // file to write request header for debug purpose

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_COOKIEJAR, $ckfile);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, $useragent);
 $html = curl_exec($ch);
 curl_close($ch);
preg_match('~<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="(.*?)" />~', $html, $viewstate);
preg_match('~<input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION"   value="(.*?)" />~', $html, $eventValidation);
$viewstate = $viewstate[1];
$eventValidation = $eventValidation[1];


$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
curl_setopt($ch, CURLOPT_COOKIEJAR, $ckfile);
curl_setopt($ch, CURLOPT_COOKIEFILE, $ckfile);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_REFERER, $url);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_STDERR, $f);
curl_setopt($ch, CURLOPT_USERAGENT, $useragent);
// Collecting all POST fields
$postfields = array();
$postfields['__EVENTTARGET'] = "";
$postfields['__EVENTARGUMENT'] = "";
$postfields['__VIEWSTATE'] = $viewstate;
$postfields['__EVENTVALIDATION'] = $eventValidation;
$postfields['ctl00$LoginPopup1$Login1$UserName'] = $username;
$postfields['ctl00$LoginPopup1$Login1$Password'] = $password;
$postfields['ctl00$LoginPopup1$Login1$LoginButton'] = 'Log In';
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields);
$ret = curl_exec($ch); // Get result after login page.

这里是简单的html dom代码

$html = file_get_contents($ret);

这是一个错误,我正在获取

Warning: file_get_contents(1): failed to open stream: No such file or directory

如有其他建议,我们将不胜感激。感谢

如果您想要将请求发送到的页面的HTML输出,请尝试将CURLOPT_RETURNTRANSFER设置为true,那么$ret应该在您输出CURL后包含页面的HTML。

我不会使用DOMDocument来解析响应,因为页面中的HTML格式可能不正确,DOMDocument会抱怨。

如果你只是在寻找链接,你可以在HTML上使用preg_match_all

正如MajorCaiger所说,您需要将CURLOPT_RETURNTRANSFER设置为true,然后用str_get_html:加载它

$html = curl_exec($ch);
$doc = str_get_html($html);

尽管如此,我认为你在这方面没有太大的成功机会,那些asp表单非常棘手。