WWW :: Mechanize :: Firefox如何提取HTML元素标签中的文本?

问题描述:

美好的一天,WWW :: Mechanize :: Firefox如何提取HTML元素标签中的文本?

你如何打印HTML标签与WWW::Mechanize::Firefox的文字?

我曾尝试:

print $_->text, '/n' for $mech->selector('td.dataCell'); 

    print $_->text(), '/n' for $mech->selector('td.dataCell'); 


    print $_->{text}, '/n' for $mech->selector('td.dataCell'); 

    print $_->content, '/n' for $mech->selector('td.dataCell'); 

记住我不想{innerhtml},但这并BTW工作。

print $_->{text}, '/n' for $mech->selector('td.dataCell'); 

上面一行的工作,但输出的只是多/n

我唯一的解决办法是使用

print $mech->xpath('//td[@class="dataCell"]/text()'); 

my $element = $mech->selector('td.dataCell'); 

my $string = $element->{innerHTML}; 

然后格式化每个dataCell

我会做:用表达

+0

修正了Xpath表达错误 – 2013-03-27 22:24:40

+1

它打印出'Mozrepl :: RemoteObject :: Instance = HASH(s0mehex)'而不是dataCells内部的文本 – surfer190 2013-03-28 06:21:26

+0

@ surfer190您必须添加'type => $ mech-> xpathResult( 'STRING_TYPE')'作为另一个参数 – CJ7 2016-07-04 23:53:18

my $node = $mech->xpath('//td[@class="dataCell"]/text()'); 

print $node->{nodeValue}; 

需要注意的是,如果你检索文字穿插着其他标记,如“TEST_1”和“Test_3”在这个例子中的HTML ...

<html> 
    <body> 
    <form name="input" action="demo_form_action.asp" method="get"> 
     <input name="testRadioButton" value="test 1" type="radio">Test_1<br> 
     <input name="testRadioButton" value="test 3" type="radio">Test_3<br> 
     <input value="Submit" type="submit"> 
    </form> 
    </body> 
</html> 

您需要通过自己的位置标记(采取任何新行考虑)中引用它们:

$node = $self->{mech}->xpath("//form/text()[2]", single=>1); 

print $node->{nodeValue}; 

它打印“TEST_1”。

+0

让我的一天!男孩。 – 2017-01-16 05:44:03

或者:

$element->{textContent};

$element->{innerText};

会工作。