WebClient.DownloadData 返回空或異常,目標站點需登入或反爬蟲。
目標站點驗證 Cookie、User-Agent、Referer 等標頭,預設 WebClient 不攜帶。
using (var client = new WebClient()) {
client.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36");
client.Headers.Add("Cookie", "你的_Cookie_內容"); // 從瀏覽器開發者工具複製
client.Headers.Add("Referer", "https://detail.zol.com.cn/");
byte[] data = client.DownloadData("https://detail.zol.com.cn/index.php?c=SearchList&keyword=聯想");
string html = Encoding.GetEncoding("GB2312").GetString(data); // 根據頁面編碼選擇
Console.WriteLine(html);
}
public class CookieWebClient : WebClient {
public CookieContainer CookieContainer { get; } = new CookieContainer();
protected override WebRequest GetWebRequest(Uri address) {
var req = (HttpWebRequest)base.GetWebRequest(address);
req.CookieContainer = CookieContainer;
return req;
}
}
// 使用
var client = new CookieWebClient();
client.Headers.Add("User-Agent", "...");
var loginData = new NameValueCollection { {"user", "u"}, {"pass", "p"} };
client.UploadValues("https://site/login", loginData); // 登入自動存 Cookie
var html = client.DownloadString("https://site/protected");
Encoding.GetEncoding("GB2312") 或 UTF8,根據 Content-Type 標頭決定。WebClient 已過時,新專案建議使用 HttpClient(.NET Core/Standard)。