Skip to content

Instantly share code, notes, and snippets.

@mehulved
Created August 1, 2012 18:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mehulved/3229614 to your computer and use it in GitHub Desktop.
Save mehulved/3229614 to your computer and use it in GitHub Desktop.
User Agent strings in more usable format
def uastring(platforms, format):
'''
This function is used to retrive User Agent String for various browsers/platforms from www.useragentstring.com.
Aim of this module is to simplify using the available data.
To find the value of the platform, visit http://useragentstring.com and get the part after /pages/
The platform parameter should be a set of one or more platforms. Supported formats are csv, json and xml.
'''
import requests
import BeautifulSoup as bsoup
url = 'http://www.useragentstring.com/pages/'
# platforms = {'Blackberry', 'Browser%20for%20S60'}
browsers = []
for platform in platforms:
try:
req = requests.get(url+platform+'/')
except requests.ConnectionError, e:
print e
if req.status_code == 200:
if len(req.text) > 0:
soup = bsoup.BeautifulSoup(req.text)
div = soup.find('div',{'id':'liste'})
list_items = div.findAll('li')
for item in list_items:
browsers.append("'"+''.join(item.findAll(text=True))+"'")
data = _create_format(browsers,format)
return data
else:
print '0 size request received'
else:
print 'HTTP Response code is {0}'.format(req.status_code)
def _create_format(browsers, format):
if format == 'csv':
return ','.join(browsers)
elif format == 'json':
return '{"browsers", browsers}'
# To be completed
elif format == 'xml':
return ''
#To be completed
else:
return 'Unsupported format'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment