user2105555 user2105555 - 2 years ago 114
Python Question

Python - Select an option from a list in Selenium

I am in the process of creating a function that allows the user to interface with a website via Python. Specifically, the user will be provided with a list of options to select, and the selected option will click on the corresponding link. Let's assume this is my code:

crop = input('\n\nSelect a crop: Wheat, Wetland rice, Dryland rice, Maize, Barley, Sorghum, Rye, Pearl millet, '
'Foxtail millet, Oat, Buckwheat, White potato, Sweet potato, Cassava, \n Yam and Cocoyam, Sugarcane, Sugarbeet,'
' Phaseolus bean, Chickpea, Cowpea, Dry pea, Gram, Pigeonpea, Soybean, Sunflower, Rapeseed, Groundnut, Oilpalm, '
'Olive, Jatropha, \n Cabbage, Carrot, Onion, Tomato, Banana, Citrus, Coconut, Cocoa, Cotton, Flax, Coffee, Tea, '
'Tobacco, Alfalfa, Pasture, Miscanthus, Switchgrass, Reed canary grass')

How would I write the next function that allows one to click on the corresponding link based on his or her answer? Which
code do I use?

I was thinking of using:


But it doesn't work.

If it helps, this is the code for the wheat link:

<input id="buttonSubmit__dim_fieldcrp2=ce_whe&amp;dimType=crp2&amp;fieldmain=main_py_six_qdns&amp;idPS=1e1d6e7d7ec3368cf13a68fc523d1ed4870e8b45&amp;idAS=0&amp;idFS=0" name="fieldcrp2=ce_whe&amp;dimType=crp2&amp;fieldmain=main_py_six_qdns&amp;idPS=1e1d6e7d7ec3368cf13a68fc523d1ed4870e8b45&amp;idAS=0&amp;idFS=0&amp;_passChanged=true&amp;_eventdim" value="Wheat" onclick="return wf_click(this);" type="submit" class="linksubmit linksubmitfalse" style="border: none;">

mgc mgc
Answer Source

I guess you can select your input element with the find_element_by_css_selector method. As it's allowed by css selectors you can access the attributes of your elements, so in your example for an input element with Wheat as value attribute:

elem = driver.find_element_by_css_selector("input[value=\"Wheat\"]")

If you have many input elements with that value you can try to be more precise by previously selecting the parent element of the input you are targeting or by adding the class name of you element in the css selector:

elem = driver.find_element_by_css_selector("input.linksubmit[value=\"Wheat\"]")

To use the value entered by the user you can use the format method of your string:


Edit: For the record, the Select(...) selenium class is used to models an element with the select html tag, allowing you afterwards to select_by_value one of it's option for example.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download