How do I create a random user agent in Python + Selenium?

痞子三分冷 提交于 2019-11-29 10:12:17

问题


How do I create a random user_agent in Chrome? I am using fake-useragent. Library here. The printed output is working but when it seems it is not loading into Chrome.

I have tried:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options


options = Options()
options.add_argument("window-size=1400,600")
from fake_useragent import UserAgent
ua = UserAgent()
a = ua.random
user_agent = ua.random
print(user_agent)
options.add_argument(f'user-agent={user_agent}')
driver = webdriver.Chrome()
driver.get('https://whoer.net/')

This does not print a random output each time.

Printed output:

Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36
(KHTML, like Gecko) Chrome/41.0.2227.1 Safari/537.36

Output user_agent according to whoer.net:

Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36


回答1:


You have not used the options that's why it doesn't work

from selenium import webdriver
from selenium.webdriver.chrome.options import Options


options = Options()
options.add_argument("window-size=1400,600")
from fake_useragent import UserAgent
ua = UserAgent()
a = ua.random
user_agent = ua.random
print(user_agent)
options.add_argument(f'user-agent={user_agent}')
driver = webdriver.Chrome(chrome_options=options)
driver.get('https://whoer.net/')
driver.quit()

After that it works, see the console and browser output




回答2:


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/")

Result of 3 consecutive execution is as follows :

  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
    
  2. Second Execution :

    Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.517 Safari/537.36
    
  3. 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
    


来源:https://stackoverflow.com/questions/48454949/how-do-i-create-a-random-user-agent-in-python-selenium

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!