如何在Python + Selenium中创建随机用户代理?

如何在Python + Selenium中创建随机用户代理?

问题描述:

如何在Chrome中创建随机的user_agent?我正在使用假用户代理. 此处的库.打印的输出正常工作,但是似乎没有加载到Chrome中.

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.

我尝试过:

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.

打印输出:

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

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

根据whoer.net输出user_agent:

Output user_agent according to whoer.net:

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

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

您尚未使用无法使用的选项

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