python-2.7 - 我无法使用 urllib、urllib2、 Mechanize 库填写字段,我想提交一个表单

标签 python-2.7 urllib2 mechanize urllib python-3.5

这是我使用 urllib 和 urllib2 的代码示例:

import urllib
import urllib2

url = 'http://example.com/schedule-appointment.php'
name =  "Name:"
phone = "Phone:"
email = "E-mail:"
office = "Office:"
rq_date = "Requested date and time:"
alt_date = "Alternative date and time:"
comments = "Reason for visit:"

values = {
         name : "Vasya",
         phone : "1234567890",
         email : "test@test.com",
         office : "Madison Ave (NYC)",
         rq_date : "01/29/2017 10:00 am" ,
         alt_date : "01/29/2017 10:00 am",
         comments : "this is a test"
       }
data = urllib.urlencode(values)
req = urllib2.Request(url, data)
response = urllib2.urlopen(req) 
the_page = response.read()
print(the_page)

并收到该消息 :{"status":false,"msg":"请填写所有字段。"}

另一个例子是 Mechanize :
import mechanize
br = mechanize.Browser() 
urlofmypage = 'http://www.example.com/schedule-appointment.php'
br.open(urlofmypage) 
print(br.geturl())
br.select_form(nr=0)
br['Name:'] = ['Vasya']   
br['Phone:'] = ['1234567890']
br['E-Mail:'] = ['test@test.com']
br['Office:'] = ['Madison Ave (NYC)']
br['Requested date and time:'] = ['01/29/2017 10:00 am']
br['Alternative date and time:'] = ['01/29/2017 10:00 am']
br['Reason for visit:'] = ['this is a test']

result = br.submit()
print(result)

知道了:
http://www.example.com/schedule-appointment.php

Traceback (most recent call last): File "/Users/vasyaiv/Desktop/Automation test Python/draft.py", line 68, in br.select_form(nr=0) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/mechanize/_mechanize.py", line 524, in select_form raise FormNotFoundError("no form matching "+description) FormNotFoundError: no form matching nr 0



有任何想法吗?

最佳答案

页面上没有表单,您尝试使用 br.open(...) 打开。
检查您的目标页面是否包含 html 代码中的表单。

更多错误:

  • 您使用了错误的控件 ID(“名称:”、“电话:”)。我怀疑,目标页面上的控件 ID 看起来像“姓名”、“电话”等。
  • 您尝试使用列表填充文本输入:
    对:br['name'] = 'Vasya' br['Phone:'] = '1234567890'
  • 关于python-2.7 - 我无法使用 urllib、urllib2、 Mechanize 库填写字段,我想提交一个表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41626131/

    相关文章:

    python-2.7 - 需要获得确切的重定向链接

    python - python中的简单登录程序

    python-2.7 - Python - 行为 - 具有相同名称的两个不同步骤

    python - 如何使用 python 将 "send"数据(图像)发送到 ImageBam.com

    python - 对二进制数据使用 Urllib2.urlopen 失败?

    ruby - 使用 Mechanize 可以使这更容易吗?

    python - 如何获取多个列表并嵌套它们?

    python - urllib2 超时

    perl - Perl 网页的缩略图截图::Mechanize

    ruby-on-rails - 设置 session 变量