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
720 views
in Technique[技术] by (71.8m points)

forms - How to simulate HTTP post request using Python Requests module?

This is the module that I'm trying to use and there is a form I'm trying to fill automatically. The reason I'd like to use Requests over Mechanize is because with Mechanize, I have to load the login page first before I can fill it out and submit, whereas with Requests, I can skip the loading stage and go straight to POSTing the message (hopefully). Basically, I'm trying to make the login process consume as little bandwidth as possible.

My second question is, after the login process and the redirection, is it possible to not fully download the whole page, but to only retrieve the page title? Basically, the title alone will tell me if the login succeeded or not, so I want to minimize bandwidth usage.

I'm kind of a noob when it comes to HTTP requests and whatnot, so any help would be appreciated. FYI, this is for a school project.

edit The first part of the question has been answered. My question now is for the second part

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Some example code:

import requests

URL = 'https://www.yourlibrary.ca/account/index.cfm'
payload = {
    'barcode': 'your user name/login',
    'telephone_primary': 'your password',
    'persistent': '1'  # remember me
}

session = requests.session()
r = requests.post(URL, data=payload)
print r.cookies

The first step is to look at your source page and identify the form element that is being submitted (use Firebug/Chrome/IE tools whatever (or just looking at the source)). Then find the input elements and identify the required name attributes (see above).

The URL you provided happens to have a "Remember Me", which although I haven't tried (because I can't), implies it'll issue a cookie for a period of time to avoid further logins -- that cookies is kept in the request.session.

Then just use session.get(someurl, ...) to retrieve pages etc...


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

...