您可以使用XML::Twig来获得它。我稍微更改了您提供的 xpath 并使其更加模块化。
use strict; use warnings;
use feature 'say';
use XML::Twig;
my $twig = XML::Twig->new();
$twig->parse(<<_HTML_
<html><body>
<div class="any_name">
<p>Element A goes here</p>
<p>Element B goes here</p>
</div>
</body></html>
_HTML_
);
for my $letter (qw(A B C)) {
foreach my $t ($twig->get_xpath("//p[string()=~/$letter goes/]")) {
say $t->xpath;
}
}
You can use a regular expression in your xpath to find the elements that match your letter. The one with text()=
didn't work in this case, because XML::Twig
matches the complete text if you use =
instead of =~ //
. Also, the correct syntax is string()
, not text()
.
The get_xpath
method returns a list of elements. I use the xpath
method on each of them, which returns the full xpath to the element. In my case that is:
/html/body/div/p[1]
/html/body/div/p[2]
There is no match for C
because I did not put it in the HTML code.