Solution found below!!
I'm trying to use uc.ChromeOptions() to do some options.add_argument() to change the user agent of my Selenium bot and a long with a few other things. However, based on the page source I got from https://httpbin.org/anything, my user-agent was not changed and is the same user-agent of my google chrome browser. Also, when my driver is first load, there are 3 tabs, one with the user-agent as the url, one with "http://disable-notifications/" (which laters turn into the correct url https://httpbin.org/anything), and one with "disable-popup-blocking/". uc.ChromeOptions() in my case is clearly not working...
Could someone pls point out where I am wrong and how I can fix this? Thank you very much. Below is my code:
from fake_useragent import UserAgent
import undetected_chromedriver as uc
if __name__ == "__main__":
opts = uc.ChromeOptions()
ua = UserAgent()
#add fake user agent to my driver
opts.add_argument(str(ua['google chrome']))
# block pop-up and notifications:
opts.add_argument("disable-popup-blocking")
opts.add_argument("disable-notifications")
driver = uc.Chrome(version_main=98, options=opts)
driver.get("https://httpbin.org/anything ")
print(driver.page_source)
CodePudding user response:
Answer:
"Use the actual command line switch to change the user agent. Command line switches all begin with -- or they'll be interpreted as an url."
from fake_useragent import UserAgent
import undetected_chromedriver as uc
if __name__ == "__main__":
ua = UserAgent()
wanted_user_agent = ua["google chrome"]
print(f"{wanted_user_agent=}")
options = uc.ChromeOptions()
options.add_argument(f"--user-agent={wanted_user_agent}")
options.add_argument("--disable-popup-blocking")
options.add_argument("--disable-notifications")
driver = uc.Chrome(options=options)
driver.get("https://httpbin.org/anything")
# it works !
actual_user_agent = driver.execute_script("return navigator.userAgent")
print(f"{actual_user_agent=}")