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

查看:545
本文介绍了如何在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.

推荐答案

使用随机 User Agent 的一种简单方法是使用Python的

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:\WebDrivers\ChromeDriver\chromedriver_win32\chromedriver.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天全站免登陆