Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send headers along in python [duplicate]

I have the following python script and I would like to send "fake" header information along so that my application acts as if it is firefox. How could I do that?

import urllib, urllib2, cookielib

username = '****'

password = '****' 

login_user = urllib.urlencode({'password' : password, 'username' : username})

jar = cookielib.FileCookieJar("cookies")

opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(jar))

response = opener.open("http://www.***.com")

response = opener.open("http://www.***.com/login.php")

response = opener.open("http://www.***.com/welcome.php", login_user)
like image 887
MarcoW Avatar asked Apr 17 '09 20:04

MarcoW


People also ask

How do you send a header in Python?

In order to pass HTTP headers into a POST request using the Python requests library, you can use the headers= parameter in the . post() function. The headers= parameter accepts a Python dictionary of key-value pairs, where the key represents the header type and the value is the header value.

How do you pass headers to a Post request?

HTTP headers let the client and the server pass additional information with an HTTP request or response. All the headers are case-insensitive, headers fields are separated by colon, key-value pairs in clear-text string format.

How do I add a header to all requests?

Fill out the Create a header fields as follows: In the Name field, enter the name of your header rule (for example, My header ). From the Type menu, select Request, and from the Action menu, select Set. In the Destination field, enter the name of the header affected by the selected action.

How do I add a header to a python request?

To add HTTP headers to a request, you can simply pass them in a dict to the headers parameter. Similarly, you can also send your own cookies to a server using a dict passed to the cookies parameter.


2 Answers

You have to get a bit more low-level to be able to do that.

request = urllib2.Request('http://stackoverflow.com')
request.add_header('User-Agent', 'FIREFOX LOL')
opener = urllib2.build_opener()
data = opener.open(request).read()
print data

Not tested.

like image 39
Deniz Dogan Avatar answered Oct 09 '22 02:10

Deniz Dogan


Use the addheaders() function on your opener object.
Just add this one line after you create your opener, before you start opening pages:

opener.addheaders = [('User-agent', 'Mozilla/5.0')]

http://docs.python.org/library/urllib2.html (it's at the bottom of this document)

like image 118
Jason Coon Avatar answered Oct 09 '22 03:10

Jason Coon