I am using the code below to change my user agent using the Selenium Webdriver. However, I can see that Google analytics can easily detect my browser and even its version every time (Firefox 54.0 in this case). Tried it with Chromedriver as well. Same result.
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")
How can I change the user agent properly?
答案 0 :(得分:1)
以下是您的问题的答案:
考虑到您的目标是使用 User Agent
更改 Selenium Webdriver
,您可以使用以下代码块每次访问网站使用 User Agent
随机 FirefoxProfile
:
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
生成的是:
Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:21.0) Gecko/20130331 Firefox/21.0
强> Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.93 Safari/537.36
强> Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; AS; rv:11.0) like Gecko
强> 如果这回答你的问题,请告诉我。