如何在Python中更改Firefox Webdriver的用户代理? [英] How to change user agent for Firefox webdriver in Python?

查看:165
本文介绍了如何在Python中更改Firefox Webdriver的用户代理?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个搜索机器人,并且希望将其从台式机更改为移动版

I'm building a search bot and i want it to change from Desktop to Mobile

我尝试使用profile.set_preferences,但是由于某种原因,它不会更改.它不会产生编译时错误,但不会更改用户代理.我也尝试过设置所需的功能,但这也不起作用.

I tried to use profile.set_preferences but for some reason it wont change. It doesn't give compiling time error but it wont change the user agent. I also tried setting the desired capabilities but that didn't work either.

if count == 0:
    browser = webdriver.Firefox(executable_path="geckodriver.exe")
else:
    profile = webdriver.FirefoxProfile()
    profile.set_preference("general.useragent.override", "Mozilla/5.0 (Android 4.4; Tablet; rv:41.0) Gecko/41.0 Firefox/41.0")
    browser = webdriver.Firefox(profile)

我希望它作为常规浏览器搜索一次,然后作为移动设备搜索,但它只是作为常规浏览器两次搜索,因此我确信我会增加计数.

I want it to search once as a regular browser and then to search as a mobile device but it just searches as a regular browser both times and i am sure that i increment count.

推荐答案

一种伪造 User Agent 的简单方法是使用FirefoxProfile(),如下所示:

A simple way to fake the User Agent would be using the FirefoxProfile() as follows :

from selenium import webdriver
from fake_useragent import UserAgent

useragent = UserAgent()
profile = webdriver.FirefoxProfile()
profile.set_preference("general.useragent.override", useragent.random)
driver = webdriver.Firefox(firefox_profile=profile, executable_path="C:\\Utility\\BrowserDrivers\\geckodriver.exe")
driver.get("http://www.whatsmyua.info/")

连续执行3次的结果如下:

Result of 3 consecutive execution is as follows :

  1. 首次执行:

  1. First Execution :

Mozilla/5.0 (Windows NT 4.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2049.0 Safari/537.36

  • 第二次执行:

  • Second Execution :

    Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.517 Safari/537.36
    

  • 第三次执行:

  • Third Execution :

    Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1309.0 Safari/537.17
    

  • 这篇关于如何在Python中更改Firefox Webdriver的用户代理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆