一段时间以前,我曾问过类似的问题,但在解析网页时仍然遇到错误。场景是系统导航到https://shop.sprouts.com/shop/flyer,并希望提取与每个类别相关的每个特殊商品。当前,当单击类别时,我会在右侧看到一个空白屏幕。 我已经尝试了以下两个选项,但得到的结果相同。
elementLeftHandSideMenu.Click();
iJavaScriptExecutor.ExecuteScript("arguments[0].click();", elementLeftHandSideMenu);
这是一个计时问题吗?我在做什么错了?
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Support.UI;
using System;
using System.IO;
using System.Linq;
using System.Reflection;
using SeleniumExtras.WaitHelpers;
using System.Threading;
using System.Collections.Generic;
using Newtonsoft.Json;
[TestClass]
public class UnitTest1
{
ChromeDriver driver;
WebDriverWait webDriverWait;
[TestInitialize]
public void Startup()
{
var chromeOptions = new ChromeOptions();
chromeOptions.AddArguments("--proxy-server='direct://'");
chromeOptions.AddArguments("--proxy-bypass-list=*");
chromeOptions.AddArguments("--start-maximized");
var path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
ChromeDriverService chromeDriverService = ChromeDriverService.CreateDefaultService(path);
driver = new ChromeDriver(chromeDriverService, chromeOptions);
webDriverWait = new WebDriverWait(driver, TimeSpan.FromSeconds(30));
}
[TestCleanup]
public void CleanUp()
{
driver.Quit();
}
[TestMethod]
public void GetSproutsWeeklyAdDetails2()
{
try
{
driver.Navigate().GoToUrl("https://shop.sprouts.com/shop/flyer");
}
catch (TimeoutException timeoutException)
{
driver.Navigate().Refresh();
}
var iJavaScriptExecutor = (IJavaScriptExecutor)driver;
webDriverWait.Until(driver1 => iJavaScriptExecutor.ExecuteScript("return document.readyState").Equals("complete"));
var elementsLeftHandSideMenu = webDriverWait.Until(ExpectedConditions.VisibilityOfAllElementsLocatedBy(
By.XPath("//ul[@class='menu sidenav']/li[@class='child']/a")));
System.Diagnostics.Debug.WriteLine(elementsLeftHandSideMenu.Count);
var items = new List<Item>();
foreach (var elementLeftHandSideMenu in elementsLeftHandSideMenu)
{
Thread.Sleep(2000);
try
{
elementLeftHandSideMenu.Click();
//iJavaScriptExecutor.ExecuteScript("arguments[0].click();", elementLeftHandSideMenu);
}
catch (Exception exception)
{
System.Diagnostics.Debug.WriteLine(exception.ToString());
}
//parsing code here does not work as the RHS shows a blank page
System.Diagnostics.Debug.WriteLine("Exit");
}
}
}
答案 0 :(得分:1)
单击元素似乎没有问题。您的网站似乎有问题。即使我手动单击,它也不是第一次加载。您可以尝试将driver.Navigate().Refresh();
从捕获中移出进行尝试,即在页面打开后或第一次单击后刷新页面。我相信它会起作用。
try
{
driver.Navigate().GoToUrl("https://shop.sprouts.com/shop/flyer");
driver.Navigate().Refresh();
}
catch (TimeoutException timeoutException)
{
driver.Navigate().Refresh();
}
如果以上代码无效,请尝试-
try
{
elementLeftHandSideMenu.Click();
driver.Navigate().Refresh();
//iJavaScriptExecutor.ExecuteScript("arguments[0].click();", elementLeftHandSideMenu);
}