以上就是给各位分享使用C#SeleniumWebdriver时忽略异常等待wait.untill,其中也会对函数进行解释,同时本文还将给你拓展C#SeleniumWebDriverWait似乎没有等待
以上就是给各位分享使用C#Selenium Webdriver时忽略异常等待wait.untill,其中也会对函数进行解释,同时本文还将给你拓展C# Selenium WebDriverWait 似乎没有等待、c# – .NET Selenium NoSuchElementException; WebDriverWait.Until()不起作用、JavaSelenium Webdriver:修改navigator.webdriver标志以防止selenium检测、Selenium c#Webdriver:等待直到元素存在等相关知识,如果能碰巧解决你现在面临的问题,别忘了关注本站,现在开始吧!
本文目录一览:- 使用C#Selenium Webdriver时忽略异常等待wait.untill()函数
- C# Selenium WebDriverWait 似乎没有等待
- c# – .NET Selenium NoSuchElementException; WebDriverWait.Until()不起作用
- JavaSelenium Webdriver:修改navigator.webdriver标志以防止selenium检测
- Selenium c#Webdriver:等待直到元素存在
使用C#Selenium Webdriver时忽略异常等待wait.untill()函数
为了检查是否存在Element和clickble,我尝试编写一个布尔方法,该方法将等待使用C#selenium的webDriverWait启用和显示该元素,如下所示:
webDriverWait等待=新的webDriverWait(驱动程序,timeSpan.fromSeconds(60));
Wait.untill(d => webElement.enabled()&& webElement.displayed());
如果以上条件没有发生,我希望该方法返回“
false”。问题是我抛出了异常。如果抛出异常,如何忽略noSuchElementException和timeOutException之类的异常?我尝试使用try
catch块,但是它没有帮助,并且引发了异常。
答案1
小编典典WebDriverWait实现DefaultWait类,该类包含公共void IgnoreExceptionTypes(params Type []
exceptionTypes)方法。
您可以使用此方法来定义在单击之前等待元素启用时要忽略的所有异常类型。
例如 :
WebDriverWait wdw = new WebDriverWait(driver, TimeSpan.FromSeconds(120));wdw.IgnoreExceptionTypes(typeof(NoSuchElementException), typeof(ElementNotVisibleException));
在前面的代码中,wait将忽略NoSuchElementException和ElementNotVisibleException异常
C# Selenium WebDriverWait 似乎没有等待
如何解决C# Selenium WebDriverWait 似乎没有等待?
我正在尝试测试我正在执行搜索的页面。执行搜索后,我首先获取表格元素,获取表格行,然后从行中获取一个或多个以做出我的断言来提取 SearchResults。
我尝试过以多种不同的方式使用 webdriverwaits,但没有成功。我设法从搜索结果中选择项目的唯一可靠方法是使用 Thread.Sleep(3000)。我们正在为我们的表格使用 PrimeNG 库。正在加载的特定表非常大,因此需要等待
硒信息:
- 硒版本:3.141.0
- 网络驱动程序类型:ChromeDriver (89.0.4389.2300)
- Web 驱动程序版本:
浏览器信息:
- 浏览器类型:Chrome
- 浏览器版本:90+(在开发机器上)
Web 驱动程序初始化代码: 我通过创建单独的页面对象和页面驱动程序来分离我的页面和自动化代码。这是以 SpecFlow Books example
为模型的BasePage 类
public class BasePage
{
protected IWebDriver Driver { get; }
protected webdriverwait Wait;
public BasePage(IWebDriver driver)
{
Driver = driver;
Wait = new webdriverwait(Driver,TimeSpan.FromSeconds(10));
}
public T As<T>() where T : BasePage
{
return (T)this;
}
public IWebElement PaginationFirst => Wait.Until(ExpectedConditions.ElementToBeClickable(By.CssSelector("button.p-paginator-first.p-paginator-element")));
public IWebElement PaginationLast => Wait.Until(ExpectedConditions.ElementToBeClickable(By.CssSelector("button.p-paginator-last.p-paginator-element")));
public IWebElement PaginationPageNumber => Wait.Until(ExpectedConditions.ElementToBeClickable(By.CssSelector("button.p-paginator-page.p-paginator-element.p-highlight")));
// Adding waits at this point meant the page elements were timing out due to not being in view.
public virtual IWebElement ResultTable()
{
Thread.Sleep(3000);
return Driver.FindElement(By.CssSelector("table"));
}
public virtual IEnumerable<IWebElement> TableLines()
{
return ResultTable().FindElements(By.CssSelector("tableRow"));
}
private void WaitUntilElementIsdisplayed(By locator)
{
webdriverwait wait = new webdriverwait(Driver,TimeSpan.FromSeconds(5));
bool Condition(IWebDriver d)
{
IWebElement e = d.FindElement(locator);
Debug.WriteLine(e.displayed);
return e.displayed;
}
wait.Until(Condition);
}
}
UserListPage 类
public class UserListPage : BasePage
{
//private readonly webdriverwait _wait;
//private readonly IWebDriver _driver;
public UserListPage(IWebDriver driver) : base(driver)
{
PageFactory.InitElements(driver,this);
}
[FindsBy(How = How.Id,Using = "headingUsers")]
public IWebElement PageTitle;
[FindsBy(How = How.Id,Using = "addUser")]
public IWebElement AddUser;
public IWebElement TxtSearchEverywhere => Wait.Until(ExpectedConditions.ElementIsVisible(By.Id("txtSearchEverywhere")));
[FindsBy(How = How.Id,Using = "col-username")]
public IWebElement ColUsername;
[FindsBy(How = How.Id,Using = "col-lastname")]
public IWebElement ColLastname;
[FindsBy(How = How.Id,Using = "col-firstname")]
public IWebElement ColFirstname;
[FindsBy(How = How.Id,Using = "col-hpicpn")]
public IWebElement ColHpicpn;
[FindsBy(How = How.Id,Using = "col-facilitycount")]
public IWebElement ColFacilitycount;
[FindsBy(How = How.Id,Using = "colRoles")]
public IWebElement ColRoles;
[FindsBy(How = How.Id,Using = "col-identitycount")]
public IWebElement ColIdentitycount;
[FindsBy(How = How.Id,Using = "colHasLogin")]
public IWebElement ColHasLogin;
[FindsBy(How = How.Id,Using = "col-onlinelogin")]
public IWebElement ColOnlinelogin;
[FindsBy(How = How.Id,Using = "col-loginstatus")]
public IWebElement ColLoginstatus;
public IEnumerable<UserRow> SearchResults => TableLines().Skip(1).Select(r => new UserRow(r));
}
HTML 代码:
<head>
<body>
<app-root>
<header>
<nav>
<main>
<app-role><button id="addRole">Add New Role</button>
<h2 id="roleTitle">Roles</h2>
<peg-admin-list>
<p-table currentpagereporttemplate="Showing {first} to {last} of {totalRecords} entries"
ng-reflect-global-filter-fields="roleName,userFriendlyName,user">
<div>
<div>
<div><span><i></i>
<input
id="txtSearchEverywhere" pinputtext="" type="search" placeholder="Search everywhere"></span><span>
<p-selectbutton>
<div role="group">
<div role="button" aria-pressed="true" title="isActive" aria-label="Active"
tabindex="0" aria-labelledby="Active">
<span>Active</span>
</div>
<div role="button" aria-pressed="false" title="isActive" aria-label="Inactive"
tabindex="0" aria-labelledby="Inactive">
<span>Inactive</span>
</div>
<div role="button" aria-pressed="false" title="isSystem" aria-label="Is System"
tabindex="0" aria-labelledby="Is System">
<span>Is System</span>
</div>
</div>
</p-selectbutton>
</span>
</div>
</div>
<div>
<table role="grid">
<thead>
<tr>
<th>
Role <p-sorticon ng-reflect-field="roleName"><ing-reflect-ng-></i>
</p-sorticon>
</th>
<th> Reviewer Role Description <p-sorticon ng-reflect-field="userFriendlyName"><ing-reflect-ng-></i>
</p-sorticon>
</th>
<th>
Users Count <p-sorticon ng-reflect-field="usersCount"><ing-reflect-ng-></i>
</p-sorticon>
</th>
<th> Is
Active <p-sorticon ng-reflect-field="isActive"><ing-reflect-ng-></i>
</p-sorticon>
</th>
<th> Is System <p-sorticon ng-reflect-field="isSystem"><ing-reflect-ng-></i>
</p-sorticon>
</th>
<th>
Role Type <p-sorticon ng-reflect-field="roleType"><ing-reflect-ng-></i>
</p-sorticon>
</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<div>A new Role Test Test with a new name </div>
</td>
<td>
<div>Check if can be seen in Admin2 bob bob bobby bob bob bob </div>
</td>
<td>
<div>4</div>
</td>
<td>
<div> Yes </div>
</td>
<tdhttps://www.jb51.cc/tag/stem/" target="_blank">stem">
<div> No </div>
</td>
<td>
<div> Admin </div>
</td>
</tr>
<tr>
<td>
<div>A new Test Role</div>
</td>
<td>
<div>Testing changes</div>
</td>
<td>
<div>2</div>
</td>
<td>
<div>Yes</div>
</td>
<tdhttps://www.jb51.cc/tag/stem/" target="_blank">stem">
<div>No</div>
</td>
<td>
<div>Admin</div>
</td>
</tr>
<tr>
<td>
<div>ADMS</div>
</td>
<td>
<div> </div>
</td>
<td>
<div>2</div>
</td>
<td>
<div>Yes</div>
</td>
<tdhttps://www.jb51.cc/tag/stem/" target="_blank">stem">
<div>No</div>
</td>
<td>
<div>Admin</div>
</td>
</tr>
</tbody>
</table>
</div>
<p-paginator>
<span>Showing 1 to 10 of 66
entries</span>
<button type="button" pripple=""https://www.jb51.cc/tag/irs/" target="_blank">irst p-paginator-element p-link p-disabled p-ripple " disabled=""
ng-reflect-ng-><span></span></button>
<button type="button" pripple=""https://www.jb51.cc/tag/dis/" target="_blank">disabled p-ripple" disabled=""
ng-reflect-ng->
<span></span>
</button>
<span>
<button type="button">1</button>
<button type="button">2</button>
<button type="button">3</button>
<button type="button">4</button>
<button type="button">5</button>
</span>
<button type="button">
<span></span>
</button>
<button type="button">
<span></span>
</button>
<p-dropdown style>
<divng-reflect-ng->
<div><input type="text"></div>
<span>10</span>
<div role="button">
<spanng-reflect-ng-></span>
</div>
</div>
</p-dropdown>
</div>
</p-paginator>
</div>
</p-table>
</peg-admin-list>
</app-role>
</main>
</nav>
</header>
</app-root>
</body>
</head>
browserDriver 类
public class browserDriver : Idisposable
{
private readonly browserDriverFactory _browserSeleniumDriverFactory;
private readonly IConfiguration _config;
private readonly ConfigurationDriver _configurationDriver;
private readonly Lazy<IWebDriver> _currentWebDriverLazy;
private readonly Lazy<webdriverwait> _waitLazy;
private readonly TimeSpan _waitDuration = TimeSpan.FromSeconds(30);
private bool _isdisposed;
public browserDriver(browserDriverFactory browserSeleniumDriverFactory,ConfigurationDriver configurationDriver,IConfiguration config)
{
_browserSeleniumDriverFactory = browserSeleniumDriverFactory;
_config = config;
_configurationDriver = configurationDriver;
_currentWebDriverLazy = new Lazy<IWebDriver>(GetWebDriver);
_waitLazy = new Lazy<webdriverwait>(Getwebdriverwait);
}
public IWebDriver Current => _currentWebDriverLazy.Value;
public webdriverwait Wait => _waitLazy.Value;
private webdriverwait Getwebdriverwait()
{
return new webdriverwait(Current,_waitDuration);
}
private IWebDriver GetWebDriver()
{
return _browserSeleniumDriverFactory.GetForbrowser(_configurationDriver.Mode);
}
public void dispose()
{
if (_isdisposed)
{
return;
}
if (_currentWebDriverLazy.IsValueCreated)
{
Current.Quit();
}
_isdisposed = true;
}
public void Navigate(string urlPart = "")
{
if (!Current.Url.EndsWith(urlPart))
{
var baseUrl = _config.GetConnectionString("BaseUrl");
Current.Manage().Window.Maximize();
Current.Navigate().GoToUrl($"{baseUrl}/{urlPart}");
RetryHelper.WaitFor(() => Current.Url.EndsWith(urlPart));
}
}
}
RoleListPageDriver 类
public class RoleListPageDriver : IRoleListDriver
{
private readonly browserDriver _browserDriver;
private readonly IHomeDriver _homeDriver;
private readonly RoleListPage _roleListPage;
public IWebElement[] HeaderColumns;
public RoleListPageDriver(browserDriver browserDriver,IHomeDriver homeDriver)
{
_browserDriver = browserDriver;
_homeDriver = homeDriver;
_roleListPage = new RoleListPage(_browserDriver.Current);
HeaderColumns = new[]
{
_roleListPage.ColRole,_roleListPage.ColDescription,_roleListPage.ColUserCount,_roleListPage.ColIsActive,_roleListPage.ColIsSystem,_roleListPage.ColRoleType
};
}
[AfterScenario()]
public void dispose()
{
_browserDriver.dispose();
}
public bool Exists(IWebElement element)
{
return element.ElementExists();
}
public bool IsLoaded()
{
return _roleListPage.PageTitle.ElementExists();
}
public void Navigate()
{
_browserDriver.Navigate("role");
}
public void Search(string searchTerm)
{
_roleListPage.TxtSearchEverywhere.Search(searchTerm);
}
public void SortColumn(string selector)
{
var element = HeaderColumns.Where(h => h.Text == selector).ToList();
if (element.Count > 0)
{
element[0].Clicks();
}
}
public bool TableColumnHeadersExist()
{
return HeaderColumns.All(header => header.ElementExists());
}
public void RoleMenuExists()
{
_roleListPage.ColRole.ElementExists();
}
public bool RoleTitleExists()
{
return _roleListPage.PageTitle.ElementExists();
}
public void RoleListSortResultShouldBeAscendingDescending(string order)
{
switch (order)
{
case Constants.ListOrder.Ascending:
_roleListPage.SearchResults.Take(5).Should().BeInAscendingOrder(r => r.RoleName);
break;
case Constants.ListOrder.Descending:
_roleListPage.SearchResults.Take(5).Should().BeInDescendingOrder(r => r.RoleName);
break;
}
}
public void SearchResultsShouldContainMatchingItems(string searchTerm)
{
var searchResult = _roleListPage.SearchResults.Take(1).Select(s => s.RoleName).ToList();
searchResult.All(str => str.Contains(searchTerm)).Should().BeTrue();
}
public void ClickOnFilterButton(string filterButton)
{
switch (filterButton)
{
case Constants.FilterButton.ActiveRoles:
_roleListPage.BtnActive.Clicks();
break;
case Constants.FilterButton.InactiveRoles:
_roleListPage.BtnInactive.Clicks();
break;
case Constants.FilterButton.IsSystemRoles:
_roleListPage.BtnIsSystem.Clicks();
break;
}
}
public void AssertOnlyActiveRolesdisplayed()
{
_roleListPage.SearchResults.Take(5).All(r => r.IsActive == "Yes").Should().BeTrue();
}
public void AssertOnlyInactiveRolesdisplayed()
{
_roleListPage.SearchResults.Take(1).All(r => r.IsActive == "No").Should().BeTrue();
}
public void AssertOnlySystemRolesdisplayed()
{
_roleListPage.SearchResults.Take(1).All(r => r.IsSystem == "Yes").Should().BeTrue();
}
public void ClickOnLastPaginationButton()
{
_roleListPage.PaginationLast.Clicks();
}
public void AssertLastPageIsdisplayed()
{
int.Parse(_roleListPage.PaginationPageNumber.Text).Should().BeGreaterOrEqualTo(3);
}
public void AssertPageTitleIsdisplayed(string title)
{
_roleListPage.PageTitle.Text.Should().BeEquivalentTo(title);
}
}
解决方法
BasePage.TableLines()
方法可以使用显式等待:
public virtual IEnumerable<IWebElement> TableLines()
{
var wait = new WebDriverWait(Driver,TimeSpan.FromSeconds(30));
var locator = By.CssSelector("table > tbody > tr");
return wait.Until(ExpectedConditions.PresenceOfAllElementsLocatedBy(locator));
}
这假设在加载数据时表格发生了某种变化。不知道加载结果时表会发生什么,我只能提供这些。
如果在您滚动时动态添加表格行,那最终将是一个完全不同的解决方案。
c# – .NET Selenium NoSuchElementException; WebDriverWait.Until()不起作用
NoSuchElementException was unhandled by user code An exception of type 'OpenQA.Selenium.NoSuchElementException' occurred in WebDriver.dll but was not handled in user code Additional information: Unable to locate element: {"method":"css selector","selector":"#assessment-472 .status-PushedToSEAS"}
它就在这里抛出:
Thread.Sleep(600); wait.Until(drv => drv.FindElement(By.CssSelector("#" + assessmentQueueId + " .status-PushedToSEAS")));
我可以看到浏览器打开,我看到它到达那一点,我可以检查元素以查看元素是否存在.它的id完全正确.
我们有这个问题很多,到目前为止解决方案是在它前面抛出Thread.Sleep(600)(或类似的时间). wait.Until()的重点是不必这样做,这使我们的测试套件变得非常长.另外,正如您在上面的示例中所看到的,有时我们甚至在将Thread.Sleep()放在它前面之后也会遇到问题,我们必须延长时间.
为什么.NET Selenium的WebDriver.Until()不起作用,并且有一种不同的方式来做同样的事情而不需要等待一段时间?同样,问题是间歇性的,这意味着它有时只会发生,它可能发生在任何数量的wait.Until()语句中,而不仅仅是显示的那个!
编辑:
这是一个类变量.
私人WebDriver等等;
它实例化如下:
this.wait = new webdriverwait(driver,TimeSpan.FromSeconds(10));
解决方法
driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(10));
为了给我这个想法,我在一个不同的问题上充分赞扬了this answer.
JavaSelenium Webdriver:修改navigator.webdriver标志以防止selenium检测
如何解决JavaSelenium Webdriver:修改navigator.webdriver标志以防止selenium检测?
从当前的实现开始,一种理想的访问网页而不被检测到的方法是使用ChromeOptions()该类向以下参数添加几个参数:
排除enable-automation
开关的集合
关掉 useAutomationExtension
通过以下实例ChromeOptions
:
Java示例:
System.setProperty("webdriver.chrome.driver", "C:\\Utility\\browserDrivers\\chromedriver.exe");
ChromeOptions options = new ChromeOptions();
options.setExperimentalOption("excludeSwitches", Collections.singletonList("enable-automation"));
options.setExperimentalOption("useAutomationExtension", false);
WebDriver driver = new ChromeDriver(options);
driver.get("https://www.google.com/");
Python范例
from selenium import webdriver
options = webdriver.ChromeOptions()
options.add_experimental_option("excludeSwitches", ["enable-automation"])
options.add_experimental_option(''useAutomationExtension'', False)
driver = webdriver.Chrome(options=options, executable_path=r''C:\path\to\chromedriver.exe'')
driver.get("https://www.google.com/")
解决方法
我正在尝试使用selenium和铬在网站中自动化一个非常基本的任务,但是以某种方式网站会检测到铬是由selenium驱动的,并阻止每个请求。我怀疑该网站是否依赖像这样的公开DOM变量https://stackoverflow.com/a/41904453/648236来检测selenium驱动的浏览器。
我的问题是,有没有办法使navigator.webdriver标志为假?我愿意尝试修改后重新尝试编译selenium源,但是似乎无法在存储库中的任何地方找到NavigatorAutomationInformation源https://github.com/SeleniumHQ/selenium
任何帮助深表感谢
PS:我还从https://w3c.github.io/webdriver/#interface尝试了以下操作
Object.defineProperty(navigator,''webdriver'',{
get: () => false,});
但是它仅在初始页面加载后更新属性。我认为网站会在执行脚本之前检测到变量。
Selenium c#Webdriver:等待直到元素存在
我想确保在webdriver开始做事之前存在一个元素。
我正在尝试使类似的东西起作用:
WebDriverWait wait = new WebDriverWait(driver, new TimeSpan(0,0,5));wait.Until(By.Id("login"));
我主要是在努力设置任意函数。
答案1
小编典典另外,您可以使用隐式等待:
driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(10);
隐式等待是告诉WebDriver在尝试查找不立即可用的一个或多个元素时,在一定时间内轮询DOM。默认设置为0。设置后,将在WebDriver对象实例的生存期内设置隐式等待。
今天关于使用C#Selenium Webdriver时忽略异常等待wait.untill和函数的分享就到这里,希望大家有所收获,若想了解更多关于C# Selenium WebDriverWait 似乎没有等待、c# – .NET Selenium NoSuchElementException; WebDriverWait.Until()不起作用、JavaSelenium Webdriver:修改navigator.webdriver标志以防止selenium检测、Selenium c#Webdriver:等待直到元素存在等相关知识,可以在本站进行查询。
本文标签: