python mechanize.browser submit()相关问题

时间:2010-03-30 10:29:42

标签: python mechanize

使用mechanize.browser模块创建一些脚本。

其中一个问题是所有其他问题都可以,但是当提交()表单时,它不起作用,

所以我发现了一些怀疑来源部分。

在html源代码中我发现了如下内容。

<form method="post" onsubmit="return loginCheck(this)" name="FRMLOGIN"/>

我在思考,loginCheck(this)在提交表单时出现问题。

但如何使用mechanize模块处理这种javascript函数,所以我可以

成功提交表格并可以收到结果吗?

下面是我目前的脚本来源。

如果有人能帮助我..很欣赏!!

# -*- coding: cp949-*-
import sys,os
import mechanize, urllib
import cookielib
from BeautifulSoup import BeautifulSoup,BeautifulStoneSoup,Tag
import datetime, time, socket
import re,sys,os,mechanize,urllib,time


br = mechanize.Browser()
cj = cookielib.LWPCookieJar()
br.set_cookiejar(cj)

# Browser options
br.set_handle_equiv(True)
br.set_handle_gzip(True)
br.set_handle_redirect(True)
br.set_handle_referer(True)
br.set_handle_robots(False)

# Follows refresh 0 but not hangs on refresh > 0
br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time=1)

# Want debugging messages?
br.set_debug_http(True)
br.set_debug_redirects(True)
br.set_debug_responses(True)

# User-Agent (this is cheating, ok?)
br.addheaders = [('User-agent', 'Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.0.6')]
br.open('http://user.buddybuddy.co.kr/Login/LoginForm.asp?URL=')
html = br.response().read()
print html

br.select_form(name='FRMLOGIN')
print br.viewing_html()
br.form['ID']='zero1zero2'
br.form['PWD']='012045'
br.submit()

print br.response().read()

3 个答案:

答案 0 :(得分:2)

mechanize根本不支持Javascript。如果您必须运行该Javascript,请查看Selenium。它提供了python绑定来控制像Firefox或IE这样的真实运行的浏览器。

答案 1 :(得分:1)

机械化忽略了

onsubmit ,没有进行javascript解释 您需要验证loginCheck();在某些有限的情况下(验证),您可以通过编程方式执行javascript的操作。

答案 2 :(得分:1)

您需要使用非维护模块DOMForm和Spidermonkey(http://pypi.python.org/pypi/python-spidermonkey)来处理javascript。或者你弄清楚loginCheck()正在做什么,并在python中提交表单之前执行它的工作。如果loginCheck()只检查登录数据的明显有效性,那应该很容易。 请注意,缺少所述表格标签的action参数。它可能是在javascript部分中给出的。

根据您的意图,仅使用urllib2可能更容易。您可以假设该网页的静态外观,只使用urllib2的方法发布数据,并使用它获得结果。

相关问题