5

Using python and selenium I need to locate and click a specific button on a webpage. While under normal circumstances this can be done with the commands

next = driver.find_element_by_css_selector(".next")
next.click()

that won't work in this case due to the webpages coding. Where both the button leading to the previous page and the one leading to the next share the same class name. Thus this code will only go back and forth between the first and second page

As far as I can tell the only way to tell the two buttons apart, is that the button leading to the previous page lies within

<li class="previous">
    #button
</li>

and the one that leads to the next page lies within

<li class="next">
    #button
</li>

Is there some way of having selenium only select and click the button that lies in the "next" li class?

The complete button code:

the previous button:

<li class="previous">
    <a class="next" rel="nofollow" onclick="qc.pA('nrForm', 'f76', 'QClickEvent', '1', 'f28'); return false;" href="">
        Previous
    </a>
</li>

the next button:

<li class="next">
    <a class="next" rel="nofollow" onclick="qc.pA('nrForm', 'f76', 'QClickEvent', '3', 'f28'); return false;" href="">
        Next
    </a>
</li>

2 Answers 2

3

I think you should use .find_element_by_xpath(). For example:

next = driver.find_element_by_xpath("//li[@class='next']/a")
prev = driver.find_element_by_xpath("//li[@class='previous']/a")

or:

next = driver.find_element_by_xpath("//a[text()='Next']")
prev = driver.find_element_by_xpath("//a[text()='Previous']")
Sign up to request clarification or add additional context in comments.

1 Comment

I have no selenium experience, and little CSS experience, but I saw a presentation about selenium once in which it was stated that using CSS is generally better than using xpath.
2

With CSS selectors:

next = driver.find_element_by_css_selector('li.next>a')

CSS Selectors are cool and useful: http://www.w3schools.com/cssref/css_selectors.asp

XPATH, not so much - it should be used only as a last resort.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.