为了账号安全,请及时绑定邮箱和手机立即绑定

输出再次是相同的标题

输出再次是相同的标题

C#
DIEA 2023-12-17 16:53:30
我的代码应该打印 中每个 elem 的标题,但它只写第一个 标题elementselem我尝试打印 中的每个 elem,它成功显示了全部 20 个不同的元素 id,但是 循环之外,但是仍然得到相同的输出! 循环置于 仅打印第一本书标题 20 次,还尝试将打印到控制台的 elementstitlexforeachforusing 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
查看完整描述

1 回答

?
心有法竹

TA贡献1866条经验 获得超5个赞

您获得相同标题的原因是您在循环中访问相同的驱动程序, foreach


我参与了foreach循环的一部分并进行了更正,即访问foreach循环中的当前元素


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

foreach (var elem in elements) {

    books.Add(new Book

        {

            Titlex = elem.FindElement(By.XPath("//h3/a")).Text,

            Price = elem.FindElement(By.XPath("//p[@class='price_color']")).Text,

            Rate = elem.FindElement(By.XPath("//article/p")).GetAttribute("class")?.Replace("star-rating ", "")

        });

}


查看完整回答
反对 回复 2023-12-17
  • 1 回答
  • 0 关注
  • 60 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信