我嘗試迭代一個 IWebElement 串列并列印每個 h2,但問題只是它列印第一個 h2
這是我的代碼
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using System;
using System.Collections.Generic;
namespace ConsoleApp
{
class Program
{
static void Main(string[] args)
{
Selenium();
}
private static void Selenium()
{
ChromeOptions options = new ChromeOptions();
options.AddArguments("start-maximized","disable-infobars", "--no-sandbox", "--disable-dev-shm-usage",
"--disable-gpu", "--disable-extensions", "--allow-running-insecure-content", "--ignore-certificate-errors",
$"--user-data-dir={AppDomain.CurrentDomain.BaseDirectory}/User Data");
using (IWebDriver driver = new ChromeDriver(options)) {
driver.Navigate().GoToUrl("https://www.amazon.com/-/es/s?i=mobile&bbn=7072561011&rh=n:7072561011,p_36:-30000,p_72:2491149011&dc&fs=true&language=es&qid=1614961572&rnid=2491147011&ref=sr_pg_");
IList<IWebElement> elements = driver.FindElements(By.ClassName("sg-col-inner"));
for (int i = 1; i < elements.Count; i )
{
Console.WriteLine(elements[i].FindElement(By.XPath("//span[@class=\"a-size-base-plus a-color-base a-text-normal\"]")).Text);
}
Console.ReadLine();
};
}
}
}
這是結果
Apple iPhone 8 GSM desbloqueado, 64GB - espacio gris (restaurado)
Apple iPhone 8 GSM desbloqueado, 64GB - espacio gris (restaurado)
Apple iPhone 8 GSM desbloqueado, 64GB - espacio gris (restaurado)
Apple iPhone 8 GSM desbloqueado, 64GB - espacio gris (restaurado)
Apple iPhone 8 GSM desbloqueado, 64GB - espacio gris (restaurado)
Apple iPhone 8 GSM desbloqueado, 64GB - espacio gris (restaurado)
Apple iPhone 8 GSM desbloqueado, 64GB - espacio gris (restaurado)
Apple iPhone 8 GSM desbloqueado, 64GB - espacio gris (restaurado)
Apple iPhone 8 GSM desbloqueado, 64GB - espacio gris (restaurado)
Apple iPhone 8 GSM desbloqueado, 64GB - espacio gris (restaurado)
Apple iPhone 8 GSM desbloqueado, 64GB - espacio gris (restaurado)
Apple iPhone 8 GSM desbloqueado, 64GB - espacio gris (restaurado)
Apple iPhone 8 GSM desbloqueado, 64GB - espacio gris (restaurado)
Apple iPhone 8 GSM desbloqueado, 64GB - espacio gris (restaurado)
我不知道發生了什么,因為我列印過元素文本并且列印正常,但是當我嘗試獲取所有 h2 時,只列印第一個 h2
uj5u.com熱心網友回復:
要從<h2>標簽列印產品名稱,您可以使用以下定位器策略:
CSS選擇器:
driver.Navigate().GoToUrl("https://www.amazon.com/-/es/s?i=mobile&bbn=7072561011&rh=n:7072561011,p_36:-30000,p_72:2491149011&dc&fs=true&language=es&qid=1614961572&rnid=2491147011&ref=sr_pg_"); IList<IWebElement> elements = driver.FindElements(By.CssSelector("h2>a>span")); foreach (IWebElement element in elements) { Console.WriteLine(element.Text); }X路徑:
driver.Navigate().GoToUrl("https://www.amazon.com/-/es/s?i=mobile&bbn=7072561011&rh=n:7072561011,p_36:-30000,p_72:2491149011&dc&fs=true&language=es&qid=1614961572&rnid=2491147011&ref=sr_pg_"); IList<IWebElement> elements = driver.FindElements(By.XPath("//h2/a/span")); foreach (IWebElement element in elements) { Console.WriteLine(element.Text); }
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/363630.html
標籤:C# 硒网络驱动程序 路径 css-选择器 网络驱动程序
