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


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.

链接地址: http://www.djcxy.com/p/39132.html

上一篇: 中继现代片段数据为空

下一篇: Python / Splinter:如何在网站上找到并选择一个选项?