我试图单击有时具有不可见叠加层的元素,尽管我可以在浏览器本身中单击它。偶尔会抛出一个异常,说该元素无法被单击,因为它被另一个元素遮盖了。
在检查SO之后,我发现其他人声称执行javascript click()调用而不是Seleniums实现WebElement.Click可以解决问题。所以我尝试了一下,页面刷新了,而不是被点击的元素。
public class Scraper : INotifyPropertyChanged
{
public List<string> Matches { get; set; } = new List<string>();
public int MatchCount { get; set; }
public string Name { get; set; }
public string StartUrl { get; set; }
public string RegexPattern { get; set; }
public By NextPageButtonSelector { get; set; }
public int WaitTimeout { get; set; } = 20;
public event EventHandler<Match> NewMatchFound;
public event PropertyChangedEventHandler PropertyChanged;
public async Task<List<Match>> ScrapeAsync(IWebDriver driver, PauseOrCancelToken pct)
{
var newMatches = new List<Match>();
try
{
await Task.Run(async () =>
{
driver.Navigate().GoToUrl(StartUrl);
do
{
await pct.PauseOrCancelIfRequestedAsync();
var mc = Regex.Matches(driver.PageSource, RegexPattern);
foreach (Match m in mc)
{
if (!Matches.Contains(m.Value))
{
newMatches.Add(m);
Matches.Add(m.Value);
MatchCount++;
OnNewMatchFound(m);
}
}
var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(WaitTimeout));
wait.Until(ExpectedConditions.ElementToBeClickable(NextPageButtonSelector));
var nextPageButton = driver.FindElement(NextPageButtonSelector);
((IJavaScriptExecutor)driver).ExecuteScript("arguments[0].scrollIntoView(true);", nextPageButton);
((IJavaScriptExecutor)driver).ExecuteScript("arguments[0].click();", nextPageButton);
} while (true);
});
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex);
}
return newMatches;
}
private void OnNewMatchFound(Match m)
{
if (NewMatchFound != null)
{
NewMatchFound(this, m);
}
}
}
答案 0 :(得分:0)
我自己解决了此问题,即使我尝试单击的元素上没有可见的覆盖层,也使用javascript单击并且WebElement.Click()无法正常工作。我的解决方案是在单击按钮之前,使用以下代码隐藏所有模糊的元素。
var obscuringElements = driver.FindElements(By.ClassName("proxy__in"));
foreach (var element in obscuringElements)
{
((IJavaScriptExecutor)driver).ExecuteScript("arguments[0].style.visibility='hidden'", element);
}