我尝试使用Python的mechanize
模块自动登录网站。以下是登录form
代码:
<TD><B>Site:</B></TD>
<TD><SELECT name="site" class="drpdwn" size=1 width="200" onChange="populateZones(this, '');"><OPTION value="">Select a site</OPTION></SELECT>
<INPUT type="hidden" name="shortsite" size="3" value=""></TD>
</TR>
<TR>
<TD><B>Zone:</B></TD>
<TD><SELECT name="zone" class="drpdwn" size=1 width="100"><OPTION value="">Select a zone</OPTION></SELECT></TD>
</TR>
<TR>
<TD><B>User ID:</B></TD>
<TD><INPUT type="text" name="user" size=20 value=""></TD>
</TR>
<TR>
<TD><B>Password:</B></TD>
<TD><INPUT type="password" name="password" size=20></TD>
</TR>
<TR>
<TD> </TD>
<TD><INPUT name="submit1" type="submit" value="Log On" style="color: #003399; font-weight: bold; font-size: 10pt">
<input name="reset1" type="reset" value="Reset" style="color: #003399; font-weight: bold; font-size: 10pt" onClick="resetform();">
</TD>
我可以毫不费力地解析和填充user
,password
和shortsite
字段。在填充zone
下拉列表时出现问题。从上面的HTML代码中可以明显看出,网页正在使用populateZones
javascript函数来填充区域。我正在寻找一种方法来强制存储在配置文件中的区域值。我过去使用HTML::Form::ForceValue
做了类似的事情。在python中是否有任何等价物?
以下是我正在努力自动登录的python脚本的摘录:
br['user'] = self.config['COMMON.USER']
br['password'] = self.config['COMMON.PASSWORD']
br['user'] = self.config['COMMON.USER']
br['password'] = self.config['COMMON.PASSWORD']
答案 0 :(得分:0)
我能够通过使用javascript来实现这一目标。共享代码可能会有所帮助:
br.select_form(predicate=self.__form_with_fields("user", "password"))
br.form.set_all_readonly(False)
br['user'] = self.config['COMMON.USER']
br['password'] = self.config['COMMON.PASSWORD']
br.form["shortsite"] = self.config['COMMON.SITE']
zone1 = br.form.find_control("zone")
#Add drop down list value dynamically like the Javascript does
mechanize.Item(zone1, {"contents": "Hurray","value": "Hurray"})
#Choose the just added option
br.form["zone"] = ["Hurray"]