How to select an item for a mechanized dropdown menu in python?

I am REALLY confused. I am basically trying to fill out a form on a website using mechanization for python. I have everything to work except the dropdown menu. What do I use to select it and what do I set for the value? I do not know if I should indicate the name of the choice or its numerical value. Help would be greatly appreciated, thanks.

Code snippet:

try: br.open("http://www.website.com/") try: br.select_form(nr=0) br['number'] = "mynumber" br['from'] = " herpderp@gmail.com " br['subject'] = "Yellow" br['carrier'] = "203" br['message'] = "Hello, World!" response = br.submit() except: pass except: print "Couldn't connect!" quit 

I am having problems with the carrier, which is a drop down menu.

+6
source share
2 answers

According to the mechanized documentation examples, you need to access the attributes of the form object, not the browser object. In addition, for the select control, you need to set the value to a list:

 br.open("http://www.website.com/") br.select_form(nr=0) form = br.form form['number'] = "mynumber" form['from'] = " herpderp@gmail.com " form['subject'] = "Yellow" form['carrier'] = ["203"] form['message'] = "Hello, World!" response = br.submit() 
+3
source

Sorry to restore a long-term recording, but that was the best answer I could find on Google, and it does not work. After more time than I have to admit, I realized this. the infrared right object of the form object, but not about the rest, and its code does not work. Here is the code that works for me (although I'm sure a more elegant solution exists):

 # Select the form br.open("http://www.website.com/") br.select_form(nr=0) # you might need to change the 0 depending on the website # find the carrier drop down menu control = br.form.find_control("carrier") # loop through items to find the match for item in control.items: if item.name == "203": # it matches, so select it item.selected = True # now fill out the rest of the form and submit br.form['number'] = "mynumber" br.form['from'] = "herpderp @gmail.com " br.form['subject'] = "Yellow" br.form['message'] = "Hello, World!" response = br.submit() # exit the loop break 
+2
source

Source: https://habr.com/ru/post/897985/


All Articles