【问题标题】:Use mobile browser in selenium without emulating the device?在 selenium 中使用移动浏览器而不模拟设备?
【发布时间】:2018-09-10 07:26:57
【问题描述】:

我尝试使用 selenium 在 python 中编写一个脚本,该脚本应该自动将图像上传到图像平台。然而,问题是,只有当您使用移动浏览器(例如 iPhone 上的 Safari)时,才会提供上传图片的功能。在一项快速研究中,我发现 selenium 支持这一点,但据我了解,只有在您模拟设备或在计算机上连接真实设备时才会提供此功能。如果您想使用 python 模拟移动浏览器,是否有其他方法(甚至可能是另一个库?)没有这样的开销(连接或模拟设备)?

【问题讨论】:

    标签: python selenium mobile browser


    【解决方案1】:

    传递正确的用户代理应该可以解决问题。移动 Chrome 示例:

    from selenium import webdriver
    from selenium.webdriver.chrome.options import Options
    
    chrome_options = Options()
    chrome_options.add_argument('--user-agent=Mozilla/5.0 (iPhone; CPU iPhone OS 10_3 like Mac OS X) AppleWebKit/602.1.50 (KHTML, like Gecko) CriOS/56.0.2924.75 Mobile/14E5239e Safari/602.1')
    driver = webdriver.Chrome(options=chrome_options)
    driver.get('https://www.google.com')
    

    【讨论】:

    • 自 2019 年 5 月 21 日起,chrome_options 现已弃用,请改用 options selenium-python.readthedocs.io/…
    • 我正在尝试在 JS 中做同样的事情,你有任何可以帮助的信息吗?我被困了 2 天
    【解决方案2】:

    指定已知的移动设备

    要使用特定设备名称启用移动仿真,“mobileEmulation”字典必须包含“deviceName”。使用 DevTools Emulation 面板中的有效设备名称作为“deviceName”的值。

    
    from selenium import webdriver
    mobile_emulation = { "deviceName": "Nexus 5" }
    chrome_options = webdriver.ChromeOptions()
    chrome_options.add_experimental_option("mobileEmulation", mobile_emulation)
    driver = webdriver.Remote(command_executor='http://127.0.0.1:4444/wd/hub',desired_capabilities = chrome_options.to_capabilities())
    

    指定单个设备属性

    还可以通过指定单个属性来启用移动仿真。要以这种方式启用移动仿真,“mobileEmulation”字典可以包含“deviceMetrics”字典和“userAgent”字符串。必须在“deviceMetrics”字典中指定以下设备指标:

    • “width” - 设备屏幕的宽度(以像素为单位)
    • “height” - 设备屏幕的高度(以像素为单位)
    • “pixelRatio” - 设备的像素比率
    • "touch" - 是否模拟触摸事件(默认为 true,通常 不需要设置)
    from selenium import webdriver
    from selenium.webdriver.chrome.options import Options
    mobile_emulation = {
        "deviceMetrics": { "width": 360, "height": 640, "pixelRatio": 3.0 },
        "userAgent": "Mozilla/5.0 (Linux; Android 4.2.1; en-us; Nexus 5 Build/JOP40D) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Mobile Safari/535.19" }
    chrome_options = Options()
    chrome_options.add_experimental_option("mobileEmulation", mobile_emulation)
    driver = webdriver.Chrome(chrome_options = chrome_options)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多