Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correctly url encoding a user agent

I'm new to Python and seem to be hitting a problem. I'm trying to urlencode a user agent string...

import urllib

UserAgent = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3 Gecko/2008092417 Firefox/3.0.3'
print 'Agent: ' + UserAgent
print urllib.urlencode(UserAgent)

Which results in...

Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3 Gecko/2008092417 Firefox/3.0.3
Traceback (most recent call last):
  File "D:\Source\SomePath\test.py", line 7, in <module>
    print urllib.urlencode(UserAgent)
  File "C:\Python26\lib\urllib.py", line 1254, in urlencode
    raise TypeError
TypeError: not a valid non-string sequence or mapping object
Press any key to continue . . .

I can only assume that although the UserAgent is being printed correctly, I'm either missing some string-escaping option on the way in or making a fundamental mistake regarding urllib.urlencode()?

like image 543
Basic Avatar asked Sep 01 '26 00:09

Basic


2 Answers

urllib.urlencode expects a mapping or sequence with two items each. as can be seen in the docs

In your code you would need to do the following:

urllib.urlencode({'Agent': UserAgent})
like image 82
Wessie Avatar answered Sep 03 '26 14:09

Wessie


Wessie beat me to it. For future reference, you can do this as well:

>>> help(urllib.urlencode)
Help on function urlencode in module urllib:

urlencode(query, doseq=0)
    Encode a sequence of two-element tuples or dictionary into a URL query string.

    If any values in the query arg are sequences and doseq is true, each
    sequence element is converted to a separate parameter.

    If the query arg is a sequence of two-element tuples, the order of the
    parameters in the output will match the order of parameters in the
    input.
like image 35
verbsintransit Avatar answered Sep 03 '26 14:09

verbsintransit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!