【问题标题】:Override geolocation using robot framework and seleniumlib使用机器人框架和 seleniumlib 覆盖地理定位
【发布时间】:2021-12-11 23:46:36
【问题描述】:

我试图使用机器人 + seleniumLib 覆盖地理定位,所有文档都提到了这个 python 代码,使用 cdp 命令,但是在这种情况下我如何导入这个代码? 我读过一些关于使用关键字“创建 Webdriver”的内容,但真的不知道它是如何工作的。 谁能帮我解决这个问题?

.py 和 .robot 文件在同一个文件夹中。

.机器人文件

***Settings***
Library             SeleniumLibrary
Library             geo.py

Suite Teardown      End    
***Variables***

***Test Cases***
Test Location
    Should appear the overrided location


***Keywords***
End
    Close All Browsers

Should appear the overrided location
    Open Browser                        https://browserleaks.com/geo       Chrome 
    Wait Until Page Contains            HTML5 Geolocation API
    Scroll Element Into View            xpath://*[@id="footer"]     
    Page Should Not Contain Element     xpath://*[@alt="BR"]    #flag img from my current country location
    Sleep                               5
    Close Browser

.py 文件

from selenium import webdriver
from selenium.webdriver.chrome.service import Service

def geoLocation_Test():
    driver = webdriver.Chrome()
    Map_coordinates = dict({
        "latitude": 41.8781,
        "longitude": -87.6298,
        "accuracy": 100
        })
    driver.execute_cdp_cmd("Emulation.setGeolocationOverride", Map_coordinates)

【问题讨论】:

    标签: selenium robotframework


    【解决方案1】:

    您不应创建浏览器的新实例。您可以通过库的driver属性获取SeleniumLibrary的驱动实例。

    下面是如何定义一个函数来在 chrome 中设置地理位置:

    from robot.libraries.BuiltIn import BuiltIn
    
    def set_geolocation(latitude, longitude, accuracy=100):
        map_coordinates = {
            "latitude": float(latitude),
            "longitude": float(longitude),
            "accuracy": int(accuracy),
        }
        selib = BuiltIn().get_library_instance("SeleniumLibrary")
        selib.driver.execute_cdp_cmd("Emulation.setGeolocationOverride", map_coordinates)
    

    以下测试通过,显示位置是伊利诺伊州芝加哥,即使那不是我的实际位置,也不是我的 VPN 连接的位置。

    *** Settings ***
    Library  geo.py
    Library  SeleniumLibrary
    
    Suite Setup     open browser  about:blank  chrome
    Suite Teardown  close browser
    
    *** Test Cases ***
    Geolocation Example
        [Setup]  set geolocation  41.8781  -87.6298  100
    
        Go to  https://my-location.org
    
        Element should contain  id=latitude   41.8781
        Element should contain  id=longitude  -87.6298
    
        capture page screenshot
    

    【讨论】:

    • 谢谢老兄,我为此浪费了数周时间,我什至不知道如何感谢...没有找到任何像这样的明确例子,太棒了
    猜你喜欢
    • 2019-06-11
    • 2017-10-04
    • 1970-01-01
    • 1970-01-01
    • 2018-12-20
    • 2017-11-07
    • 2021-03-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多