我编写了一个脚本,该脚本收集从数据库读取的缓冲区内的所有 URL,检查该页面是否仍然存在,并使用 HTTP::Tiny 从缓冲区中删除 URL(如果该 URL 无法访问或返回无效)。
问题是 HTTP::Tiny 删除左锚标记,例如此处无效的文本。这些链接已突出显示,但显然无法单击它们。这是 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>}{$1}sg;
my $sql = "not described here";
write_sql($dbh,$sql,$ref->{'id'});
}
}
这是经过上面代码处理后的示例字符串。
This week, perhaps the most interesting articles include "<a>Finding \r\n that Windows is superior to Linux is biased</a>," "<a href=\"http://www.example.com/content/view/118693\">How \r\n to set up DNS for Linux VPNs</a>," and "<a href=\"http://www.example.com/content/view/118664 \">Writing \r\n an Incident Handling and Recovery Plan</a>."
请注意,字符串“Finding \r\n that Windows is better to Linux is有偏见”曾经是带有 href 的有效链接,但删除函数将所有这些内容删除并保留了锚标记。
这是预期的效果吗?也许我应该在 HTTP::Tiny 中使用不同的库或函数?
你误解了什么delete
做。您的代码所做的就是删除href
Mojo::DOM 表示中该 DOM 元素的属性。它与 HTTP::Tiny 无关。
你真正想做的是call ->strip https://metacpan.org/pod/Mojo::DOM#strip on the <a>
元素,这会将其从 DOM 中删除,但保持其内容不变。
既然您已经在使用 Mojo::DOM,您也可以使用Mojo::用户代理 https://metacpan.org/pod/Mojo::UserAgent。无需引入另一个 UA 模块。无论如何,您已经安装了整个 Mojolicious。
您可以使用HEAD 请求 https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/HEAD而不是检查资源是否可用的 GET 请求。无需下载整个内容,标头就足够了。
您的代码(没有数据库部分)可以简化为这样。
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!
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)