Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python/Splinter: How to find and select an option on a site?

Using Python and Splinter, currently, I need to define exactly what text, option1 to click on when an option is found on a page:

from splinter import Browser
browser = Browser('chrome')

browser.find_option_by_text(option1).first.click()

But if the option1 is not there, how can I fall back and choose any next option available rather than having to define it?

And is it possible to just find an option on a page and choose any first, available option encountered, without having to define the option?

Thank you in advance and will be sure to upvote/accept answer

like image 758
Jo Ko Avatar asked Apr 24 '17 02:04

Jo Ko


1 Answers

You could get all the options in the page. So if the first search for option1 is empty, you can resume to the next options available.

selected_option = browser.find_option_by_text(option1) or browser.find_by_tag('option')
selected_option = selected_option.first if selected_option else None

The inline if in the second line is there because the find_by_tag can also return an empty list if there are no options at all in that page.

The find_by_tag method is the response for both questions, since you can use it as a fallback or collect all the options at once.

like image 190
Fernando Cezar Avatar answered Sep 28 '22 07:09

Fernando Cezar