c# - Console doesn't write any value
问题描述
I'm trying to scrape books.toscrape.com
everything seems perfect, but it doesn't output anything to console.
I'm sure about the XPaths are correct, and syntax is right.
I don't see any errors, or warnings.
Don't have any clue what i can try for this problem.
using System;
using System.Windows;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using System.Data;
using System.Collections.Generic;
namespace book_scraping
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
DataTable table = new DataTable();
public MainWindow()
{
InitializeComponent();
}
string user_url;
class Book
{
public string Titlex { get; set; }
public string Price { get; set; }
public string Rate { get; set; }
}
public void Scrape()
{
var books = new List<Book>();
IWebDriver driver = new FirefoxDriver();
user_url = Textbox1.Text;
int.TryParse(Textbox2.Text, out var x);
for (int i = 1; i < x; i++)
{
driver.Url = "http://" + user_url + "/catalogue/" + "page-" + i + ".html";
var element = driver.FindElements(By.XPath("//article[@class='product_pod']"));
foreach (var elements in element) {
var book = new Book
{
Titlex = driver.FindElement(By.XPath("//h3/a")).Text,
Price = driver.FindElement(By.XPath("//p[@class='price_color']")).Text,
Rate = driver.FindElement(By.XPath("//article/p")).GetAttribute("class")?.Replace("star-rating ", ""),
};
foreach (var a in books)
{
Console.WriteLine($"{a.Titlex} {a.Price} {a.Rate}");
}
}
}
}
private void Button_Click(object sender, RoutedEventArgs e)
{
Scrape();
}
}
}
I expect the output of title,price,rate as text like hello world 50 three, or something similar
解决方案
你的书单是空的,试试这个
books.Add(new Book
{
Titlex = driver.FindElement(By.XPath("//h3/a")).Text,
Price = driver.FindElement(By.XPath("//p[@class='price_color']")).Text,
Rate = driver.FindElement(By.XPath("//article/p")).GetAttribute("class")?.Replace("star-rating ", ""),
});
代替:
var book = new Book
{
Titlex = driver.FindElement(By.XPath("//h3/a")).Text,
Price = driver.FindElement(By.XPath("//p[@class='price_color']")).Text,
Rate = driver.FindElement(By.XPath("//article/p")).GetAttribute("class")?.Replace("star-rating ", ""),
};
推荐阅读
- php - $mysqli->escape_string - 可以在不指定确切字段名称的情况下使用吗
- java - 在庞大的数据集中计算唯一的 URL(150+ 十亿)
- vue.js - vuejs dynamic input collection with wrong values
- ubuntu - whoami returns user but usermod complains it doesn't exist
- r - Forecasting of a dynamac's package object
- matlab - Built-in MATLAB command to find unknown upper limit that makes an integral equal to zero?
- vim - Can VIM automatically close NERDTree when deleting a buffer?
- powershell - Powershell Invoke-Restmethod 由于 SSL/TLS 安全通道(Smartsheets API)而中止
- r - 计算 data.frame 上的字符位置
- android - 在 Firebase 中将 SMS OTP 身份验证与电子邮件链接验证身份验证相关联