如何在Selenium中使用代理示例
using System;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
class Program
{
static void Main()
{
string api = ""; // 这里填写你购买后生成的API网址,如果没有或者不会,请找客服 如:http://www.soyunip.com/api?ddbh=s8349453653
try
{
// 获取代理IP
string ip = GetProxyIp(api);
// 如果返回是多行多个代理信息的,需要解析一下
string[] ips = ip.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries); // 这里返回多行多个代理IP,默认是以\r\n分隔符的
if (ips.Length == 0 || string.IsNullOrEmpty(ips[0]))
{
throw new Exception("No valid IP address found in response");
}
string myip = ips[0]; // 这里取第一个代理IP 实际应用时,根据需要自己选择
// 配置ChromeOptions以使用代理
ChromeOptions options = new ChromeOptions();
options.AddArgument($"--proxy-server=http://{myip}");
// 初始化ChromeDriver
using (IWebDriver driver = new ChromeDriver(options))
{
// 下面举例是你要访问的网站链接
string url = "http://myip.ipip.net";
driver.Navigate().GoToUrl(url);
// 打印页面源代码
Console.WriteLine(driver.PageSource);
}
}
catch (Exception ex)
{
Console.Error.WriteLine("An error occurred: " + ex.Message);
}
}
static string GetProxyIp(string apiUrl)
{
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(apiUrl);
request.Method = "GET";
request.Timeout = 10000; // 超时设置为10秒
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
if (response.StatusCode != HttpStatusCode.OK)
{
throw new Exception("Failed to get IP address: HTTP error code : " + (int)response.StatusCode);
}
using (Stream stream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(stream))
{
return reader.ReadToEnd().Trim(); // 返回的内容如:125.26.21.154:13456
}
}
}
catch (Exception ex)
{
Console.Error.WriteLine("Error fetching proxy IP: " + ex.Message);
return "";
}
}
}