【问题标题】:Parse element from redirected page with PHP Simple HTML DOM Parser使用 PHP Simple HTML DOM Parser 从重定向页面解析元素
【发布时间】:2021-01-06 17:41:05
【问题描述】:

我正在尝试从重定向页面解析标题。这是我的代码:

<?php

include_once('simple_html_dom.php');

$link="https://duckduckgo.com/?q=!ducky+google";
$html = file_get_html($link);

foreach ($html->find('title') as $text){
    echo $text->plaintext."<br/>";

}
?>

结果应该是“Google”。谢谢

【问题讨论】:

  • “重定向页面”到底是什么意思?您可能想让我们知道您的实际问题是什么,而不是仅仅发布您拥有的代码和您想要的内容?运行代码时会发生什么?请阅读How to create a Minimal, Reproducible ExampleHow do I ask a good question 并相应地编辑您的问题。
  • @MagnusEriksson 我的情况很简单。我有一个输入字段,在提交时应该从duckduckgo搜索引擎中找到的第一个页面返回一个标题及其链接。例如:您在输入字段“堆栈溢出”中提交,返回应该是:标题:堆栈溢出;网址:duckduckgo.com/?q=!ducky+stackverflow 就是这样。但现在就我而言,当我回显 $text->plaintext 时,它会显示一个空白页。我希望你现在能理解我:)

标签: php redirect simple-html-dom domparser


【解决方案1】:

使用 Simle DOM 后找到 URL 重定向页面:

<?php 

$url="https://duckduckgo.com/?q=!ducky+google";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // Must be set to true so that PHP follows any "Location:" header
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$a = curl_exec($ch); // $a will contain all headers

$url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL); // This is what you need, it will return you the last effective URL



echo $url; // your url hire *_*  AppsGM
?>

现在使用您的代码

    <?php

include_once('simple_html_dom.php');


$html = file_get_html($url);

foreach ($html->find('title') as $text){
    echo $text->plaintext."<br/>";

}
?>

【讨论】:

    【解决方案2】:

    我不确定我是否 100% 理解了您的要求,但这里有几件事可以帮助您继续前进!

    三件事:

    1. “!”在 $link 中将您重定向到谷歌。如果您想访问鸭子结果页面,请将其删除。
    2. simple-html-dom 无法访问鸭子结果页面。您是否尝试回显 $html 以查看您得到了什么?我试过了,但被验证码阻止了……你需要弄清楚如何绕过它。只有这样,您才能访问这些标题。
    3. 最后,您的标题是 H2 ...使用解析器访问 h2 标记可能更容易。

    这有帮助吗? 如果您找到绕过验证码的方法,请告诉我!我有兴趣:)

    【讨论】:

      猜你喜欢
      • 2023-03-15
      • 1970-01-01
      • 2016-04-09
      • 2011-02-26
      • 1970-01-01
      • 1970-01-01
      • 2015-05-09
      • 1970-01-01
      • 2011-06-17
      相关资源
      最近更新 更多