python's mechanize和forms:javascript字符串返回

python's mechanize and forms: javascript string returned

本文关键字:forms javascript 字符串 返回 mechanize python      更新时间:2023-09-26

我正在尝试访问http://forum.kriminala.net通过机械化和解析我的收件箱消息。

从html代码中,我可以看到登录表单位于主页的嵌套iframe中:

<iframe src="login/" style="width: 100%; height: 124px; border-bottom: 2px solid #DDE5EA; box-shadow: 0px 0px 10px #ccc;" frameborder="0" vspace="0" scrolling="no" hspace="0">
...
<form action="" class="auth_form" method="post">
<input type="hidden" name="referer" value="http%3A%2F%2Fforum.kriminala.net%2F">
<input type="text" class="text_input" name="username" placeholder="Имя пользователя" value="" tabindex="1">
<input type="password" class="text_input" name="password" placeholder="Пароль" tabindex="2">
<input type="checkbox" id="autologin" checked="checked" name="autologin" tabindex="3">
<label for="autologin">Запомнить меня</label>
<input type="submit" class="submit_button" id="submit_button" name="login" value="" tabindex="3">
</form>
...
</iframe>

所以我导航到http://forum.kriminala.net/login,在那里找到表格,并将其与我的用户名和密码一起提交,将结果输出到文件中(查看我是否成功登录)。

br=mechanize.Browser()
br.open("http://forum.kriminala.net/login/")
br.select_form(nr=0)
br["username"]="12n"
br["password"]="123456"
response=br.submit()
htmlpage=open("response.html","w")
htmlpage.writelines(response.get_data())
htmlpage.close()

然而,我在文件中看到的是:

<script type="text/javascript">
window.top.location = 'http://forum.kriminala.net/';
</script>

我的下一个想法是,也许我应该手动转到主图像,所以我在机械化中打开主页,将其放入一个html文件中,在浏览器中打开,但该文件看起来仍然像我没有登录。

我该如何处理?

附言:我是一个十足的Python迷,所以也许我只是不知道该用谷歌搜索什么来获得答案。如果是这样的话,请告诉我正确的方向。

谢谢!

一切似乎都很好。生成的页面会用JavaScript将您重定向到主页(或者可能重定向到登录前的任何位置),这是一件合理的事情。由于"浏览器"中没有JavaScript,您需要手动导航到任何需要的位置。

登录的实际结果应该是其中一个响应中的Set-Cookie:标头。您需要在随后的请求标头中使用该cookie,以使服务器认为您已登录。有关更多理论,请参阅HTTPcookie@wikipedia。

使用mechanize在Python中模拟浏览器似乎有相关的代码可以在mechanize中执行,特别是br.set_cookiejar()命令。