我撰寫了一個腳本,該腳本收集從資料庫讀取的緩沖區中的所有 URL,檢查該頁面是否仍然存在,如果 URL 不可訪問或回傳無效,則使用 HTTP::Tiny 從緩沖區中洗掉該 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優于 Linux is biased”曾經是帶有href的有效鏈接,但洗掉函式將所有這些都去掉并留下了錨標記。
這是預期的效果嗎?也許我應該在 HTTP::Tiny 中使用不同的庫或函式?
uj5u.com熱心網友回復:
你誤解了什么delete。您的代碼所做的就是href從 Mojo::DOM 表示中的該 DOM 元素中洗掉屬性。它與 HTTP::Tiny 無關。
您真正想要做的是呼叫元素->strip<a>,將其從 DOM 中洗掉,但保持其內容不變。
由于您已經在使用 Mojo::DOM,因此您也可以使用Mojo::UserAgent。無需拉入另一個 UA 模塊。無論如何,您已經安裝了整個 Mojolicious。
您可以使用HEAD 請求而不是 GET 請求來檢查資源是否可用。不需要下載整個東西,標題就足夠了。
您的代碼(沒有 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!
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/425551.html
