问题
During my tests, we need to click on links that open webpages in new tab. In some cases, we see the test fail due to inclusion of multiple space or tab characters in the title text. One of the examples of such titles are -
"Looking for more information about US?${SPACE}${SPACE}Find out more from ... Get your questions answered."
I am trying to switch to the window using the partial text "Looking for more information about US" instead of using the whole title text. But so far could not find a way to do that.
My current codes are as follows:
Test for "Frequently Asked Question"" Link at the bottom panel
Hide Promo Carousel
execute javascript window.scrollTo(0,document.body.scrollHeight)
Click External Link and Return partial link:Frequently Asked Questions Looking for more information about us? Find out more from ...... Get your questions answered.
and the keyword is :
Click External Link and Return
[Arguments] ${Element} ${ExtUrl}
${CurrTitle}= get title
click element ${Element}
sleep 5s
run keyword and continue on failure select window ${ExtUrl}
sleep 1s
run keyword and continue on failure select window ${CurrTitle}
Is there a way to locate and navigate to the window using partial text from the title? Kindly suggest if there is any way in robot framework, Python or JavaScript to achieve this.
回答1:
Using the below example the custom keyword will use the current browser and then using a pattern search for the tab and select it. If there are more or less than 1 result, it will fail.
*** Settings ***
Library SeleniumLibrary
Library Collections
*** Test Cases ***
Select Window Using Partial Title
Open Browser http://www.google.com chrome
Click Element link:About CTRL
Sleep 5s
Title Should Be Google
Switch Window Using Title Pattern Over*
Title Should Be Over - Google
[Teardown] Close Browser
*** Keywords ***
Switch Window Using Title Pattern
[Arguments] ${title_pattern}
${current_title} Get Title # Save the current tab title
${window_titles} Get Window Titles # Cycles through the tabs.
Switch Window ${current_title} # Restores the original tab focus
${match_count} Get Match Count ${window_titles} ${title_pattern}
Run Keyword If '${match_count}'=='0' Fail No Browser Tabs found that meet the "${title_pattern}" pattern.
Run Keyword If '${match_count}'>'1' Fail Too many Browser Tabs found that meet the "${title_pattern}" pattern.
${matches} Get Matches ${window_titles} ${title_pattern}
Switch Window ${matches}[0]
来源:https://stackoverflow.com/questions/59569335/how-to-navigate-to-new-browser-window-using-partial-title-text-using-either-pyth