Mae
Mae

Reputation: 433

XPath: Select first 5 elements

At the moment I am scraping some data from another website and I'm having problems about how to get the first 5 elements only.

$travelguide_row = 
$travelguide_xpath->query('//div[@class="traveltips"]//span|//div[@class="traveltips"]//p');

Can I add more syntaxes after //span and //p? If yes, how?

Upvotes: 6

Views: 2742

Answers (1)

har07
har07

Reputation: 89305

You can use predicate expression [position() < 6] to achieve that. The following XPath should get you the first 5 elements matched by your original XPath expression :

(//div[@class="traveltips"]//span|//div[@class="traveltips"]//p)[position() < 6]

Upvotes: 7

Related Questions