解決方法如下!!
我正在嘗試使用 uc.ChromeOptions() 來做一些 options.add_argument() 來更改我的 Selenium 機器人的用戶代理以及其他一些東西。但是,根據我從https://httpbin.org/anything獲得的頁面源,我的用戶代理沒有更改,并且與我的 google chrome 瀏覽器的用戶代理相同。此外,當我的驅動程式第一次加載時,有 3 個選項卡,一個以用戶代理作為 url,一個以“http://disable-notifications/”(后來變成正確的 url https://httpbin. org/anything),一個帶有“disable-popup-blocking/”。uc.ChromeOptions() 在我的情況下顯然不起作用......
有人可以指出我錯在哪里以及如何解決這個問題嗎?非常感謝。下面是我的代碼:
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)
uj5u.com熱心網友回復:
回答:
“使用實際的命令列開關來更改用戶代理。命令列開關都以 -- 開頭,否則它們將被解釋為 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=}")
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/438446.html
標籤:Python 硒 网页抓取 用户代理 未检测到的chromedriver
