2015-06-17 59 views
1

我是Mojolicious的新手。我相信這可能是一個設置問題,但它被吃掉了整整一天。我試圖運行這個簡單的測試代碼找不到使用Mojo的模塊:: DOM

#!/usr/bin/perl 

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

my $ua = Mojo::UserAgent->new(); 

$ua->get('https://stackoverflow.com/questions/26353298/find-links-containing-bold-text-using-wwwmechanize')->res->dom('a div')->ancestors('div.spacer')->each(sub { say $_->all_text }); 

,我發現在這個位置

find links containing bold text using WWW::Mechanize

,並與

Can't locate object method "ancestors" via package "Mojo::Collection" at ./test4.pl line 10. 

我已經卸載並重新安裝失敗10萬次,嘗試了不同的軟件包安裝選項(cpan,cpanm,direct link等)。沒有骰子。我有點困惑,Mojo :: Collection模塊似乎沒有一個「祖先」方法(繼承或不),但我見過其他幾個像這樣的例子,似乎使用相同的方法以相同的方式。這不僅僅是「祖先」模塊,問題似乎也在影響其他一些方法。

我在使用Mojolicious軟件包6.11的Linux Mint上使用perl 5.18.2。

感謝您的任何幫助。

回答

3

這是非常困難的調試這樣一個長鏈語句,你好得多它拆分成單獨的步驟

傳遞參數給dom方法是一樣的調用find與參數上DOM對象。 find返回Mojo::Collection,這是合理的,因爲它是與CSS選擇器匹配的節點集。該ancestors方法僅適用於單個節點,所以你必須選擇一個出來的東西,如firstlast,或使用each

這是你的代碼的重寫產生什麼,我認爲是處理它們一次一個預期結果

use strict; 
use warnings; 
use 5.010; 

use open qw/ :std :encoding(UTF-8) /; 

use Mojo; 

my $url = 'http://stackoverflow.com/q/26353298'; 

my $ua = Mojo::UserAgent->new->max_redirects(3); 
my $dom = $ua->get($url)->res->dom; 

my $divs = $dom->find('a div'); 

printf "%d matching div elements:\n\n", $divs->size; 

my $n; 
for my $div ($divs->each) { 
    my $spacers = $div->ancestors('div.spacer'); 
    for my $spacer ($spacers->each) { 
    printf "%2d -- %s\n\n", ++$n, $spacer->all_text; 
    } 
} 

輸出

20 matching div elements: 

1 -- Stack Exchange Podcast #65: The Word Has Two Meanings, You See 

2 -- PIVOTing into a new career: please welcome Taryn Pratt, bluefooted Community … 

3 -- 0 Can't locate module(s) using Mojo::DOM 

4 -- 0 tiny runable www::Mechanize examples for the beginner 

5 -- 2 Perl WWW::Mechanize and authenticated proxy 

6 -- 0 How to process a simple loop in Perl's WWW::Mechanize? 

7 -- 1 not able to click a button in www::mechanize perl 

8 -- 0 Perl - Mechanize? - How to get all links in a page up to a specific 「delimiter」 text 

9 -- 2 Why am I getting gibberish content using Perl's WWW::Mechanize? 

10 -- 1 Getting error in accessing a link using WWW::Mechanize 

11 -- 3 Perl WWW::Mechanize Web Spider. How to find all links 

12 -- 0 What is the best way to extract unique URLs and related link text via perl mechanize? 

13 -- 0 perl WWW::Mechanize file upload error 
+1

謝謝!現在正在工作。我不瞭解第一個和最後一個節點業務。現在我明白它正在向我傳遞一組數據結構中的節點。 是的,原來是有點太緊湊,開始與(尤其是因爲我現在只是現在熟悉自己的Mojo)。 再次感謝。 –

+1

@JimSimmonds:我很高興提供幫助:Mojolicious是一個不錯的框架。我只希望它支持XPath表達式以及CSS選擇器。 'first'和'last'只是從Mojo :: Collection中提取一個Mojo :: DOM對象的例子。你也可以使用'each'來返回一個節點列表,你可以像數組引用那樣索引它,所以'$ collection-> first'和'$ collection - > [0]'是一樣的。 – Borodin

+0

@JimSimmonds :我建議你看看[***當某人回答我的問題時該怎麼辦?***](http://stackoverflow.com/help/someone-answers) – Borodin