【问题标题】:retrieve href attributes from url with php使用 php 从 url 检索 href 属性
【发布时间】:2018-10-11 11:16:19
【问题描述】:

我想检索website1提供的主页url上所有锚标签中的href属性,将网站爬取一级深度,并检索爬取页面上找到的所有锚标签中的href属性,但它没有显示任何东西。我使用的函数是findAndCompare

<html>
<body>

<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
website: <input type="text" name="website1"><br>
website: <input type="text" name="website2"><br>
<input type="submit" name="submit">
</form>

</body>
</html> 

<?php
  if(isset($_POST['submit']))
  {
    // form has been submitted
    $form_data = $_POST['website1'];
    findAndCompare($form_data);

  }
  else
  {}

function findAndCompare($url){

// Create a DOM parser object
$dom = new DOMDocument();

$dom->loadHTML($url);

// Iterate over all the <a> tags
foreach($dom->getElementsByTagName('a') as $link) {
        // Show the <a href>
        echo $link->getAttribute('href');
        echo "<br />";
}
}

?>

【问题讨论】:

  • 作为建议:jquery/javascript 会更适合这项任务
  • 你想如何使用带有外部 URL @ThisGuyHasTwoThumbs 的 javascript 来做到这一点?
  • @Syscall 好吧,这取决于抓取目标是否是相同域 - 或者它是否设置了正确的标头 - 但您可以以这种方式回显和抓取

标签: php url dom href


【解决方案1】:

loadHTML() 方法需要 HTML 源代码,而不是 URL。您可以改为使用 loadHTMLFile() 加载源代码:

function findAndCompare($url){

    // Create a DOM parser object
    $dom = new DOMDocument();

    // load HTML from URL
    $dom->loadHTMLFile($url);

    // Iterate over all the <a> tags
    foreach($dom->getElementsByTagName('a') as $link) {
        // Show the <a href>
        echo $link->getAttribute('href');
        echo "<br />";
    }
}

【讨论】:

    猜你喜欢
    • 2012-10-13
    • 1970-01-01
    • 2019-08-18
    • 2022-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-03
    • 1970-01-01
    相关资源
    最近更新 更多