简体   繁体   English

使用Mechanize和Python登录到堆栈溢出

[英]Logging into Stack Overflow with Mechanize and Python

I have been using this guide to help me: http://www.pythonforbeginners.com/cheatsheet/python-mechanize-cheat-sheet/ 我一直在使用本指南来帮助我: http : //www.pythonforbeginners.com/cheatsheet/python-mechanize-cheat-sheet/

I want to log into Stack Overflow and print out my login response using Mechanize in Python. 我想使用Python中的Mechanize登录到Stack Overflow并打印出我的登录响应。 I have been troubleshooting to find a form name to select and enter my information into, but am currently getting an error "ValueError: at least one argument must be supplied to specify control" because I am trying to print out all forms and controls to help me figure out what I need to choose from. 我一直在进行故障排除,以查找一个表单名称以选择并输入我的信息,但是当前收到错误消息“ ValueError:必须提供至少一个参数以指定控件”,因为我正在尝试打印所有表单和控件以提供帮助我弄清楚我需要选择什么。

   import mechanize

   #make browser object
   browser = mechanize.Browser()

  #open stack login page
  browser.open("http://stackoverflow.com/users/login#login-in")

  #print all the forms on the page
  print("\n Printing all forms on page...\n")
  for form in browser.forms():
          print("Form Name:", form.name)
          print form
  print("\n Done printing forms...\n")

  #printing the controls of each form

  browser.form=list(browser.forms())[0]

  print("\n Printing controls of form 0 \n")
  for control in browser.form.controls:
          print control
          print "type=%s, name=%s, value=%s" % (control.type, control.name, browser[control.name])

  browser.form=list(browser.forms())[1]

  print("\n Printing controls of form 1 \n")
  for control in browser.form.controls:
          print control
          print "type=%s, name=%s, value=%s" % (control.type, control.name, browser[control.name])

  browser.form=list(browser.forms())[2]

  print("\n Printing controls of form 2 \n")
 for control in browser.form.controls:
          print control
          print "type=%s, name=%s, value=%s" % (control.type, control.name, browser[control.name])

 print("\n Done printing all controls \n")

It looks like there are 3 forms on the page, but they do not contain the email and password inputs I am looking for to login. 该页面上似乎有3种形式,但是它们不包含我要登录的电子邮件和密码输入。 What am I doing wrong? 我究竟做错了什么?

Login forms for SO appear to use extensive JavaScript. SO的登录表单似乎使用了广泛的JavaScript。 Note that all of the buttons related to login on the page you posted call JavaScript functions. 请注意,您发布的页面上与登录相关的所有按钮都调用JavaScript函数。 mechanize can not execute JavaScript and therefore won't show the content you need. mechanize无法执行JavaScript,因此不会显示您需要的内容。

You could drive a browser using Selenium with Python bindings . 您可以使用带有Python绑定的 Selenium驱动浏览器。 You could also switch to doing everything in JavaScript using CasperJS . 您还可以切换到使用CasperJS在JavaScript中进行所有操作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM