在 Selenium 中更改 Google Chrome 用户代理的方法? [英] Way to change Google Chrome user agent in Selenium?

查看:39
本文介绍了在 Selenium 中更改 Google Chrome 用户代理的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找出一种方法,每当我在这个特定脚本中通过 Selenium(在 Python 中)打开 Chrome 时,Chrome 页面会自动打开并选择另一个用户代理 - 在这种情况下,Microsoft Edge Mobile(但我将从桌面访问它).

I'm trying to figure out a way whereby whenever I open up Chrome via Selenium (in Python) in this particular script, the Chrome page automatically opens up with another user agent selected - in this case, Microsoft Edge Mobile (but I will be accessing it from the desktop).

所以,经过一些研究,我已经能够拼凑出以下代码,我认为这些代码会在 Chrome 中执行用户代理切换,然后打开一个新的 Bing.com 页面:

So, after doing some research, I've been able to piece together the following code, which I thought would execute a user-agent switch in Chrome and then open up a new Bing.com page:

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")
driver = webdriver.Chrome(chrome_options=opts)
driver = webdriver.Chrome("D:\_")
driver.get("https://www.bing.com/")

但是,代码似乎不起作用,并在打开指定网页之前停止.我相当确定代码的前半部分已关闭,但我不太确定如何关闭.任何和所有帮助将不胜感激.

However, the code doesn't seem to be working and stops before opening up the designated webpage. I'm fairly certain the first half of code is off, but I'm not quite sure how. Any and all help would be deeply appreciated.

推荐答案

使用随机用户代理的一种简单方法是使用 Python 的 fake_useragent 模块如下:

A simple way to use a random User Agent would be using Python's fake_useragent module as follows :

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

options = Options()
ua = UserAgent()
userAgent = ua.random
print(userAgent)
options.add_argument(f'user-agent={userAgent}')
driver = webdriver.Chrome(chrome_options=options, executable_path=r'C:WebDriversChromeDriverchromedriver_win32chromedriver.exe')
driver.get("https://www.google.co.in")
driver.quit()

连续执行3次的结果如下:

Result of 3 consecutive execution is as follows :

  1. 第一次执行:

  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

  • 第二次执行:

  • Second Execution :

    Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.517 Safari/537.36
    

  • 第三次执行:

  • 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
    

  • 这篇关于在 Selenium 中更改 Google Chrome 用户代理的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆