本文整理汇总了Python中user_agents.parse方法的典型用法代码示例。如果您正苦于以下问题:Python user_agents.parse方法的具体用法?Python user_agents.parse怎么用?Python user_agents.parse使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类user_agents
的用法示例。
在下文中一共展示了user_agents.parse方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: is_supported
# 需要导入模块: import user_agents [as 别名]
# 或者: from user_agents import parse [as 别名]
def is_supported(self, user_agent_string):
"""Check user agent against configured exclusions.
"""
user_agent_obj = user_agents.parse(user_agent_string)
browser_ok = True
for rule in self.exclusions:
if rule in ["mobile", "tablet", "touchcapable", "pc", "bot"]:
if (
(rule == "mobile" and user_agent_obj.is_mobile)
or (rule == "tablet" and user_agent_obj.is_tablet)
or (rule == "touchcapable" and user_agent_obj.is_touch_capable)
or (rule == "pc" and user_agent_obj.is_pc)
or (rule == "bot" and user_agent_obj.is_bot)
):
browser_ok = False
elif rule in user_agent_string:
browser_ok = False
return browser_ok
示例2: transform
# 需要导入模块: import user_agents [as 别名]
# 或者: from user_agents import parse [as 别名]
def transform(self, X: dt.Frame):
def get_ua_info(ua_string):
from user_agents import parse
ua = parse(ua_string)
return ua.browser.family, ua.os.family, ua.device.family, ua.is_mobile, ua.is_tablet
ua_column_names = ['ua', 'user-agent', 'user_agent', 'useragent']
col_name = X.names[0]
if col_name in ua_column_names:
newnames = ("browser", "os", "device", "is_mobile", "is_tablet")
Y = X[col_name].to_list()[0]
Z = dt.Frame([get_ua_info(x) for x in Y], names=[f"{col_name}_{s}" for s in newnames])
X.cbind(Z)
return X
else:
return X.to_pandas().iloc[:, 0]
示例3: parse_user_agent
# 需要导入模块: import user_agents [as 别名]
# 或者: from user_agents import parse [as 别名]
def parse_user_agent(user_agent: Union[None, str]) -> Dict[str, str]:
result: Dict[str, str] = {
'os': 'Other',
'browser': 'Other'
}
if user_agent is None:
raise AttributeError('User-Agent header not found!')
if 'CaptiveNetworkSupport' in user_agent and 'wispr' in user_agent:
result['os']: str = 'Mac OS X'
result['browser']: str = 'Captive'
else:
device = user_agent_parse(user_agent_string=user_agent)
result['os']: str = device.os.family
result['browser']: str = device.browser.family
return result
# endregion
# region Check Host header
示例4: connectionMade
# 需要导入模块: import user_agents [as 别名]
# 或者: from user_agents import parse [as 别名]
def connectionMade(self):
log.debug("HTTP connection made.")
try:
user_agent = parse(self.headers['user-agent'])
self.clientInfo["clientos"] = user_agent.os.family
self.clientInfo["browser"] = user_agent.browser.family
try:
self.clientInfo["browserv"] = user_agent.browser.version[0]
except IndexError:
self.clientInfo["browserv"] = "Other"
except KeyError:
self.clientInfo["clientos"] = "Other"
self.clientInfo["browser"] = "Other"
self.clientInfo["browserv"] = "Other"
self.clientInfo["clientip"] = self.client.getClientIP()
self.plugins.hook()
self.sendRequest()
self.sendHeaders()
if (self.command == 'POST'):
self.sendPostData()
示例5: read
# 需要导入模块: import user_agents [as 别名]
# 或者: from user_agents import parse [as 别名]
def read(self):
"""Reads the robots.txt URL and feeds it to the parser."""
try:
headers = {'User-Agent': user_agent, }
request = urllib.request.Request(self.url, None, headers)
f = urllib.request.urlopen(request,timeout=self.timeout)
# f = urllib.request.urlopen(self.url) #! original code
except urllib.error.HTTPError as err:
if err.code in (401, 403):
self.disallow_all = True
elif err.code >= 400 and err.code < 500:
self.allow_all = True
else:
raw = f.read()
self.parse(raw.decode("utf-8").splitlines())
# Notes for the future:
# 1. The bandwidth usage is undoubtedly (much) smaller because gzip encoding is used
# 2. A lightweight proxy could be used for accurate bandwidth, and header editing
# Safe search options
示例6: region
# 需要导入模块: import user_agents [as 别名]
# 或者: from user_agents import parse [as 别名]
def region(request, region_alias):
if "_" in region_alias:
region_alias, area_alias = region_alias.split("_")
region_item = get_object_or_404(models.Region, alias=area_alias, parent_region__alias=region_alias)
else:
region_alias, area_alias = region_alias, None
region_item = get_object_or_404(models.Region, alias=region_alias)
user_agent = user_agents.parse(request.META['HTTP_USER_AGENT'])
if region_item.status or (region_item.level == 2 and region_item.parent_region.status):
return render(request, 'area.html', context={
"region": region_item,
"region_alias": region_alias,
"area_alias": repr(area_alias) if area_alias is not None else 'null',
"is_mobile": user_agent.is_mobile,
})
else:
# Get parent region if exist else current
region_item = region_item.parent_region or region_item
return render(request, 'no_area.html', context={
'region_item': region_item
})
示例7: get_agent_information
# 需要导入模块: import user_agents [as 别名]
# 或者: from user_agents import parse [as 别名]
def get_agent_information(user_agent_string):
"""
Get additional information about the user agent, such as browser and OS
:param user_agent_string: the user-agent string sent by the browser
:return: the additional information produced by parsing the string
"""
user_agent = parse(user_agent_string)
if user_agent.is_pc:
device_type = device_types.COMPUTER
elif user_agent.is_tablet:
device_type = device_types.TABLET
elif user_agent.is_mobile:
device_type = device_types.MOBILE
else:
device_type = device_types.UNKNOWN
return user_agent.browser, user_agent.os, device_type,
示例8: device
# 需要导入模块: import user_agents [as 别名]
# 或者: from user_agents import parse [as 别名]
def device(ip=False):
"""Returns an object describing the device the user is using, or the
user's IP address if the optional keyword argument 'ip' is
True.
"""
if ip:
return this_thread.current_info['clientip']
if 'headers' in this_thread.current_info:
ua_string = this_thread.current_info['headers'].get('User-Agent', None)
if ua_string is not None:
response = ua_parse(ua_string)
else:
response = None
else:
response = None
return response
示例9: process_request
# 需要导入模块: import user_agents [as 别名]
# 或者: from user_agents import parse [as 别名]
def process_request(self, req, resp, *args):
req.context["remote_addr"] = ipaddress.ip_address(req.access_route[0])
if req.user_agent:
req.context["user_agent"] = parse(req.user_agent)
else:
req.context["user_agent"] = "Unknown user agent"
示例10: test_user
# 需要导入模块: import user_agents [as 别名]
# 或者: from user_agents import parse [as 别名]
def test_user(self, request=None):
ua_header = request.META['HTTP_USER_AGENT']
user_agent = parse(ua_header)
if user_agent.is_mobile:
return self.mobile
if user_agent.is_tablet:
return self.tablet
if user_agent.is_pc:
return self.desktop
return False
示例11: is_bot
# 需要导入模块: import user_agents [as 别名]
# 或者: from user_agents import parse [as 别名]
def is_bot():
''' Is the current request from a web robot? '''
ua = request.headers.get('User-Agent')
return ua and user_agents.parse(ua).is_bot
示例12: is_bot
# 需要导入模块: import user_agents [as 别名]
# 或者: from user_agents import parse [as 别名]
def is_bot(self):
ua = self.user_agent
return ua and user_agents.parse(ua).is_bot
示例13: get_google_location_data
# 需要导入模块: import user_agents [as 别名]
# 或者: from user_agents import parse [as 别名]
def get_google_location_data(self, lat, lon):
"""Use Google's Maps API to collect location info for the provided latitude and longitude.
Google returns a bunch of JSON with a variety of location data. This function returns
Google's pre-formatted `formatted_address` key for a human-readable address.
"""
google_maps_url = "https://maps.googleapis.com/maps/api/geocode/json?latlng={},{}&sensor=false&key={}".format(lat, lon, self.GEOLOCATE_TOKEN)
r = requests.get(google_maps_url)
maps_json = r.json()
if r.ok:
try:
if "error_message" in maps_json:
print("[!] Google Maps returned an error so using Gophish coordinates. Error: {}".format(maps_json['error_message']))
return "{}, {}".format(lat, lon)
first_result = maps_json['results'][0]
if "formatted_address" in first_result:
return first_result["formatted_address"]
# In case that key is ever unavailable try to assemble an address
else:
components = first_result['address_components']
country = town = None
for c in components:
if "country" in c['types']:
country = c['long_name']
if "locality" in c['types']:
town = c['long_name']
if "administrative_area_level_1" in c['types']:
state = c['long_name']
return "{}, {}, {}".format(town, state, country)
except Exception as e:
print("[!] Failed to parse Google Maps API results so using Gophish coordinates.")
print("L.. Error: {}".format(e))
return "{}, {}".format(lat, lon)
else:
print("[!] Failed to contact the Google Maps API so using Gophish coordinates. Status code: {}".format(r.status_code))
return "{}, {}".format(lat, lon)
示例14: index
# 需要导入模块: import user_agents [as 别名]
# 或者: from user_agents import parse [as 别名]
def index(request):
"""
index home page
:param request:
:return:
"""
# 记录访问来源
log_refer_request(request)
# PC 版、手机版适配
user_agent = parse(request.META.get('HTTP_USER_AGENT', ''))
index_number = 10
if user_agent.is_pc:
index_number = 8
# 判断是否登录用户
user = get_login_user(request)
# 默认的渲染列表,区分是否登录用户
if user is None:
articles = Article.objects.filter(status='active', site__star__gte=20).order_by('-id')[:index_number]
else:
user_sub_feeds = get_user_sub_feeds(user.oauth_id)
if not user_sub_feeds:
logger.warning(f'用户未订阅任何内容:`{user.oauth_name}')
articles = Article.objects.filter(status='active', site__name__in=user_sub_feeds).order_by('-id')[:index_number]
context = dict()
context['articles'] = articles
context['user'] = user
context['github_oauth_key'] = settings.GITHUB_OAUTH_KEY
if user_agent.is_pc:
return render(request, 'index.html', context)
else:
return render(request, 'mobile/index.html', context)
示例15: get_ua
# 需要导入模块: import user_agents [as 别名]
# 或者: from user_agents import parse [as 别名]
def get_ua(self, request):
ua_string = request.META.get('HTTP_USER_AGENT', '')
if len(ua_string) > 200:
ua_string = ua_string[:200]
# 解析为user_agent
user_agent = user_agents.parse(ua_string)
# 判断浏览器
bw = user_agent.browser.family
# 判断操作系统
s = user_agent.os.family
# 输出
return bw