Php Dom Parser错误Uncaught SyntaxError

时间:2015-08-13 13:47:05

标签: php parsing dom

所以我一直试图让它发挥作用,它正在发挥作用。我在Imgur上尝试过,但我无法让它在这个网站上工作......我需要帮助。

<?php   
# create and load the HTML
include('simple_html_dom.php');
$html = new simple_html_dom();
$html = file_get_html('https://www.ivory.co.il/');

foreach($html->find('a') as $e) 
    echo $e->href . '<br>';

    foreach($html->find('img') as $e)
    echo $e->src . '<br>';

echo $html->save();
?>

这是我在控制台中获得的内容。

enter image description here

2 个答案:

答案 0 :(得分:0)

这对我有用。您是否尝试使用不同的URL,只是为了交叉检查功能?

答案 1 :(得分:0)

该网站非常棘手!如果仔细观察,您会发现第一次访问时会设置一个cookie并将您重定向回主页。默认情况下,simple_html_dom不记得cookie并且不遵循重定向(因此您永远不会抓取实际的网站数据)。

要修复它,您需要使用CURL并将其设置为:

  • 允许重定向
  • 存储Cookie
  • 根据每个请求发回cookie。

我已经修改了你的代码:

<?php   
# create and load the HTML
include('simple_html_dom.php');

// Initialize CURL
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://www.ivory.co.il/');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);

// This tells CURL to follow any redirects
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

// Don't verify the SSL certificate (can be removed if website has valid cert)
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

// Here you tell CURL to save all cookies to the file cookiejar.txt
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookiejar.txt');

// Here you tell CURL to send the stored cookies with each request you make
curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookiejar.txt');

$data = curl_exec($ch);
curl_close($ch);

// Load the HTML source code from a string
$html = str_get_html($data);

// Your code goes here!
foreach($html->find('a') as $e){
    echo $e->href . '<br>';
}

foreach($html->find('img') as $e){
    echo $e->src . '<br>';
}

希望能帮到你!