Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
400 views
in Technique[技术] by (71.8m points)

python - Use mechanize to submit form without control name

I'm trying to use mechanize for python to submit a form but the form control I need to fill in doesnt have a name assigned to it.

<POST https://sample.com/anExample multipart/form-data
  <HiddenControl(post_authenticity_token=) (readonly)>
  <HiddenControl(iframe_callback=) (readonly)>
  <TextareaControl(<None>=)>>

The control I'm trying to edit is the last control in the above object, <TextareaControl(<None>=)>.

I've looked at the documentation and cant seem to find a way to assign a value to that control since it doesnt have a name associated with it.

  forms = [f for f in br.forms()]
  print forms[2].controls[5].name

Outputs "None"

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

So, I'll grant you, this one was pretty tough to figure out. Had to literally take a look at the mechanize code itself to figure out. Unfortunately, I couldn't test it for sure on an actual form item without a name attribute, though I can do so if you provide the site you're trying to pull, or you can do it yourself.

The forms objects honestly aren't implemented so well for usability. The only way I can see for you edit a nameless form control's value is by using the form's set_value method:

class HTMLForm:

    # <...>

    set_value(value,
          name=None, type=None, kind=None, id=None, nr=None,
          by_label=False,  # by_label is deprecated
          label=None)

So, what you'd do here to set the control you're looking for is use the nr argument to grab it, using the index of the control in the form. Unfortunately, you can't use negative integers to grab controls from the back, so to grab the last form you'd have to do something along the lines of nr=len(myform.controls)-1.

In any case, what you can then do here is use that set_value method, and you should be set, as such:

forms[2].set_value("LOOK!!!! I SET THE VALUE OF THIS UNNAMED CONTROL!", 
                       nr=5)

and that should work for you. Let me know how it goes.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...