Skip to main content
 首页 » 编程设计

python之使用 Selenium 更改浏览器类型和版本

2025年02月15日8insus

我正在使用下面的代码通过 Selenium Webdriver 更改我的用户代理。但是,我可以看到 Google Analytics 每次都可以轻松检测到我的浏览器甚至它的版本(在本例中为 Firefox 54.0)。也用 Chromedriver 试过了。相同的结果。

from selenium import webdriver 
from selenium.webdriver.common.keys import Keys 
from selenium.webdriver.chrome.options import Options 
from fake_useragent import UserAgent 
 
useragent = ua.random 
 
#Chrome 
''' 
opts.add_argument('"'+useragent+'"') 
driver =  webdriver.Chrome(chrome_options=opts) 
''' 
 
#Firefox 
profile = webdriver.FirefoxProfile() 
profile.set_preference("general.useragent.override", useragent) 
driver = webdriver.Firefox(profile) 
driver.get("www.mywebsite.com") 

如何正确更改用户代理?

请您参考如下方法:

这是您问题的答案:

考虑到您的目标是使用 Selenium Webdriver 更改 User Agent,您可以使用代码每次使用 FirefoxProfile 随机 User Agent 访问网站:

from selenium import webdriver 
from selenium.webdriver.firefox.firefox_binary import FirefoxBinary 
from fake_useragent import UserAgent 
 
binary = FirefoxBinary('C:\\Program Files\\Mozilla Firefox\\firefox.exe') 
useragent = UserAgent() 
profile = webdriver.FirefoxProfile() 
profile.set_preference("general.useragent.override", useragent.random) 
driver = webdriver.Firefox(firefox_profile=profile, firefox_binary=binary, executable_path="C:\\Utility\\BrowserDrivers\\geckodriver.exe") 
driver.get("http://www.whatsmyua.info/") 

观察

在三个不同的运行中,User Agents 生成的是:

  1. Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:21.0) Gecko/20130331 Firefox/21.0
  2. Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36(KHTML,如 Gecko)Chrome/27.0.1453.93 Safari/537.36
  3. Mozilla/5.0(Windows NT 6.1;WOW64;Trident/7.0;AS;rv:11.0)如 Gecko

如果这回答了您的问题,请告诉我。