Python Auto Fill with Mechanize

痴心易碎 提交于 2019-11-27 16:57:35

问题


Could someone help me or share some code to auto fill a login with mechanize (http://wwwsearch.sourceforge.net/mechanize/)? I want to make a python script to log me into my favorite sites when I run it.

Thanks!


回答1:


This will help you to login to one site and download a page for example:

import mechanize
br=mechanize.Browser()
br.open('http://www.yourfavoritesite.com')
br.select_form(nr=0) #check yoursite forms to match the correct number
br['Username']='Username' #use the proper input type=text name
br['Password']='Password' #use the proper input type=password name
br.submit()
br.retrieve('https://www.yourfavoritesite.com/pagetoretrieve.html','yourfavoritepage.html')

This script presumes that your login form is the first of the page and the input names are Username and Password.
You could also select your form by name with:

br.select_form(name="thisthing")

Please, adapt this script to your favorite site login page.
As well pointed by AlexMartelli, this script should be generalized to handle different sites with some config parameters.




回答2:


Each of your favorite sites probably has different forms (form number, and names of user and password fields) and one hopes you use different usernames and passwords on each (using the same user and password on many sites means that if one of the sites is cracked, your identity is now compromised "everywhere" -- quite a mess!).

So, you can either hardcode all of these parameters, as in @systempuntoout's answer, or write a little configuration text file (for example in the format supported by ConfigParser) with all this info for each site, so that you can load the configuration when your script starts, and write a "log_me_in" function, just once, that takes the sitename as the parameter and looks up and uses the parameters that depend on it.

If you have a lot of "favorite sites", so that loading all their info perceptibly slows your startup time, then you may even want to consider persisting that info more smartly (e.g. in a sqlite table) so it can be looked up rapidly for just one or a few sites given their names as the "key" to use.



来源:https://stackoverflow.com/questions/3516655/python-auto-fill-with-mechanize

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!