最近有個需求需要進行爬蟲處理,又開始研究C#,要抓取中油價格,告知相關人員申請補助,廢話不多說,直接上程式碼
測試過anglesharp與htmlagilitypack都不行似乎是因為這個價格欄位是動態欄位,最後選擇使用Selenium,這個方式會開啟Edge,抓完後關閉
dotnet add package Selenium.WebDriver --version 4.10.0
using System;
using System.Collections.Generic;
using OpenQA.Selenium;
using OpenQA.Selenium.Edge;
namespace ConsoleApplication_Selenium
{
class Program
{
static void Main(string[] args)
{
using (IWebDriver driver = new EdgeDriver())
{
driver.Navigate().GoToUrl("https://www.cpc.com.tw/");
IList priceElements = driver.FindElements(By.CssSelector("ul.today_price_ct b.price"));
IList nameElements = driver.FindElements(By.CssSelector("ul.today_price_ct b.name"));
for (int i = 0; i < priceElements.Count; i++)
{
string name = nameElements[i].Text;
string price = priceElements[i].Text;
Console.Write("Name: " + name + ", ");
Console.WriteLine("Price: " + price);
}
}
}
}
}
沒有留言:
張貼留言