Perl:HTTP::Tiny 删除留下损坏的锚标签

Perl: HTTP::Tiny delete leaves broken anchor tags

我编写了一个脚本,用于收集从数据库读取的缓冲区中的所有 URL,检查该页面是否仍然存在,并使用 HTTP::Tiny 从中删除 URL缓冲区无法访问或 returns 无效。

问题是 HTTP::Tiny 删除了无效的左锚标记,例如此处的文本。 link 突出显示,但显然无法单击它们。这是 HTTP::Tiny delete 的缺陷还是我用错了?

my $html_full = $ref->{'fulltext'}; # $ref is a pointer to the database
my $dom_buff = Mojo::DOM->new($html_buff);
foreach my $ele ($dom_buff->find('a[href]')->each) {
  my $url = $ele->attr('href');
  my $response = HTTP::Tiny->new(default_headers => { Accept => '*/*' })->get($url);
  if ($response->{success}) {
     $success_fulltext_urls{$ref->{'id'}}{$url} = 1;
  } else {
     delete $ele->attr->{href};
     $html_buff = $dom_buff;
     $html_buff =~ s{<a>(.*?)</a>}{}sg;
     my $sql      = "not described here";
     write_sql($dbh,$sql,$ref->{'id'});
  }
}

这是一个示例字符串,经过上面的代码处理后。

This week, perhaps the most interesting articles include &quot;<a>Finding \r\n  that Windows is superior to Linux is biased</a>,&quot; &quot;<a href=\"http://www.example.com/content/view/118693\">How \r\n  to set up DNS for Linux VPNs</a>,&quot; and &quot;<a href=\"http://www.example.com/content/view/118664 \">Writing \r\n  an Incident Handling and Recovery Plan</a>.&quot;

注意字符串“Finding \r\n that Windows is superior to Linux is biased”曾经是一个有效的带有href的link,但是删除函数剥离所有内容并留下锚标签。

这是预期的效果吗?也许我应该在 HTTP::Tiny?

中使用不同的库或函数

您误解了 delete 的作用。您的所有代码所做的就是从 Mojo::DOM 表示中的 DOM 元素中删除 href 属性。与HTTP::Tiny.

无关

您真正想要做的是在 <a> 元素上 call ->strip,将其从 DOM 中删除,但保持其内容不变。

既然您已经在使用 Mojo::DOM,您也可以使用 Mojo::UserAgent。无需拉入另一个 UA 模块。无论如何,您已经安装了整个 Mojolicious。

您可以使用 a HEAD request 而不是 GET 请求来检查资源是否可用。不用全部下载,headers就够了。

您的代码(没有 DB 部分)可以简化为这样。

use strict;
use warnings;
use Mojo::DOM;
use Mojo::UserAgent;

my $ua = Mojo::UserAgent->new;
my $dom = Mojo::DOM->new(<DATA>);

foreach my $element ($dom->find('a[href]')->each) {
    $element->strip
        unless $ua->head($element->attr('href'))->res->is_success;
}

print $dom;

__DATA__
This <a href="http://example.org">link works</a>.
This <a href="http://httpstat.us/404">one does not</a>!

这输出:

This <a href="http://example.org">link works</a>. This one does not!