Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 875
Mae Avatar asked Jan 28 '16 03:01

Mae


People also ask

How do I select an element using XPath?

The intent is to locate the fields using XPath. Go to the First name tab and right click >> Inspect. On inspecting the web element, it will show an input tag and attributes like class and id. Use the id and these attributes to construct XPath which, in turn, will locate the first name field.

How do you select the second element with the same XPath?

For example if both text fields have //input[@id='something'] then you can edit the first field xpath as (//input[@id='something'])[1] and the second field's xpath as (//input[@id='something'])[2] in object repository.

What is text () in XPath?

XPath text() function is a built-in function of the Selenium web driver that locates items based on their text. It aids in the identification of certain text elements as well as the location of those components within a set of text nodes. The elements that need to be found should be in string format.


1 Answers

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]
like image 154
har07 Avatar answered Sep 30 '22 21:09

har07