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)
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.
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.
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.
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With