Selenium C#网页爬取:无法获取Bidrl商品浏览量问题求助
问题:无法通过Selenium提取商品浏览量数值
我需要访问Bidrl平台的某商品页面,提取“Item Has Been Viewed”字段中的纯数字浏览量。目前已成功获取商品标题,但尝试多种定位方式均无法获取浏览量数据,附上当前代码,请求解决:
using OpenQA.Selenium; using OpenQA.Selenium.Chrome; namespace WebScraperDemo { class Program { static void Main(string[] args) { IWebDriver driver = new ChromeDriver(); driver.Navigate().GoToUrl("https://www.bidrl.com/auction/high-end-auction-3920-w-capitol-ave-ste-150-west-sac-monday-sept-25-at-630pm-134960/item/camplux-portable-tankless-water-heater-158-gpm-17730099/"); // 成功获取标题 string text1 = driver.FindElement(By.XPath("//span[@ng-bind-html='item.title']")).Text; System.Diagnostics.Debug.WriteLine(text1); // 无法获取浏览量 string text2 = driver.FindElement(By.XPath("//div[@class='viewed-item']")).Text; System.Diagnostics.Debug.WriteLine(text2); } } }
解决方法
1. 核心问题:元素加载延迟
页面渲染时,浏览量元素可能未同步加载完成,直接调用FindElement会抛出找不到元素的异常,需要添加显式等待确保元素可被定位。
2. 修改后的代码
using OpenQA.Selenium; using OpenQA.Selenium.Chrome; using OpenQA.Selenium.Support.UI; using System; using System.Text.RegularExpressions; namespace WebScraperDemo { class Program { static void Main(string[] args) { using (IWebDriver driver = new ChromeDriver()) { driver.Navigate().GoToUrl("https://www.bidrl.com/auction/high-end-auction-3920-w-capitol-ave-ste-150-west-sac-monday-sept-25-at-630pm-134960/item/camplux-portable-tankless-water-heater-158-gpm-17730099/"); // 获取标题 string title = driver.FindElement(By.XPath("//span[@ng-bind-html='item.title']")).Text; System.Diagnostics.Debug.WriteLine($"标题:{title}"); // 显式等待浏览量元素加载,最长等待10秒 WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10)); IWebElement viewElement = wait.Until(d => d.FindElement(By.ClassName("viewed-item"))); // 提取文本中的纯数字 string viewText = viewElement.Text; string viewCount = Regex.Match(viewText, @"\d+").Value; System.Diagnostics.Debug.WriteLine($"浏览量:{viewCount}"); } } } }
3. 关键说明
- 添加
OpenQA.Selenium.Support.UI命名空间,使用WebDriverWait实现显式等待,避免因元素未加载导致的异常。 - 使用正则表达式
\d+匹配文本中的数字,直接提取浏览量数值。 - 用
using包裹ChromeDriver,确保驱动资源自动释放。
内容的提问来源于stack exchange,提问作者user1508129
相关产品推荐
相关产品推荐

