输出再次是相同的标题

我的代码应该打印 中每个 elem 的标题,但它只写第一个 标题elementselem


我尝试打印 中的每个 elem,它成功显示了全部 20 个不同的元素 id,但是 循环之外,但是仍然得到相同的输出! 循环置于 仅打印第一本书标题 20 次,还尝试将打印到控制台的 elementstitlexforeachfor


using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Data;

using System.Windows.Documents;

using System.Windows.Input;

using System.Windows.Media;

using System.Windows.Media.Imaging;

using System.Windows.Navigation;

using System.Windows.Shapes;

using OpenQA.Selenium;

using System.Threading;

using OpenQA.Selenium.Firefox;  


namespace book_scraper_2

{

    /// <summary>

    /// Interaction logic for MainWindow.xaml

    /// </summary>

    /// 


    public class Book

    {


        public string Titlex { get; set; }

        public string Price { get; set; }

        public string Rate { get; set; }



    }

    public partial class MainWindow : Window

    {

        public MainWindow()

        {

            InitializeComponent();

        }


        readonly IWebDriver driver = new FirefoxDriver();

        string user_url;

        public void Scrape() {

            var books = new List<Book>();

            user_url = Text1.Text;

            int.TryParse(Text2.Text, out var x);

            for (int i =1; i < x; i ++) {

                driver.Url = "http://" + user_url + "/catalogue/" + "page-" + i + ".html";

                var elements = driver.FindElements(By.XPath("//article[@class='product_pod']"));

            }


        }


我希望看到网站上所有书籍的标题


注:使用的网站是books.toscrape.com


DIEA
浏览 121回答 1
1回答

心有法竹

您获得相同标题的原因是您在循环中访问相同的驱动程序, foreach我参与了foreach循环的一部分并进行了更正,即访问foreach循环中的当前元素var elements = driver.FindElements(By.XPath("//article[@class='product_pod']"));foreach (var elem in elements) {&nbsp; &nbsp; books.Add(new Book&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Titlex = elem.FindElement(By.XPath("//h3/a")).Text,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Price = elem.FindElement(By.XPath("//p[@class='price_color']")).Text,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Rate = elem.FindElement(By.XPath("//article/p")).GetAttribute("class")?.Replace("star-rating ", "")&nbsp; &nbsp; &nbsp; &nbsp; });}
打开App,查看更多内容
随时随地看视频慕课网APP