首頁  >  文章  >  後端開發  >  如何使用 Selenium 和 Python 更改 Chrome 中的用戶代理程式?

如何使用 Selenium 和 Python 更改 Chrome 中的用戶代理程式?

Barbara Streisand
Barbara Streisand原創
2024-10-26 03:05:03939瀏覽

How to Change the User Agent in Chrome with Selenium and Python?

使用Selenium 更改Chrome 中的用戶代理

在自動化需要特定瀏覽器配置的任務時,更改Chrome 中的用戶代理至關重要。這可以使用 Selenium 和 Python 來實現。

要啟用使用者代理開關,請修改選項設定:

<code class="python">from selenium import webdriver
from selenium.webdriver.chrome.options import Options

opts = Options()
opts.add_argument("user-agent=Mozilla/5.0 (Windows Phone 10.0; Android 4.2.1; Microsoft; Lumia 640 XL LTE) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Mobile Safari/537.36 Edge/12.10166")</code>

此參數指定所需的使用者代理程式。在本例中,它模擬 Microsoft Edge Mobile。

但是,提供的程式碼不會載入網頁。要解決此問題:

<code class="python">driver = webdriver.Chrome(chrome_options=opts)
driver.get("https://www.bing.com/")</code>

Python 的 fake_useragent 模組允許隨機選擇用戶代理:

<code class="python">from fake_useragent import UserAgent

ua = UserAgent()
user_agent = ua.random</code>

這提供了一個隨每次執行而變化的隨機用戶代理。

<code class="python">options.add_argument(f'--user-agent={user_agent}')
driver = webdriver.Chrome(chrome_options=options)</code>

現在,多個頁面載入的使用者代理程式將會不同。

以上是如何使用 Selenium 和 Python 更改 Chrome 中的用戶代理程式?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn