我的代碼應該打印 中每個 elem 的標題,但它只寫第一個 標題elementselem我嘗試打印 中的每個 elem,它成功顯示了全部 20 個不同的元素 id,但是 循環(huán)之外,但是仍然得到相同的輸出! 循環(huán)置于 僅打印第一本書標題 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']")); } }我希望看到網(wǎng)站上所有書籍的標題注:使用的網(wǎng)站是books.toscrape.com
1 回答

心有法竹
TA貢獻1866條經(jīng)驗 獲得超5個贊
您獲得相同標題的原因是您在循環(huán)中訪問相同的驅動程序, foreach
我參與了foreach循環(huán)的一部分并進行了更正,即訪問foreach循環(huán)中的當前元素
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 ", "")
});
}
- 1 回答
- 0 關注
- 159 瀏覽
添加回答
舉報
0/150
提交
取消