1 通过HttpWebRequest获取网页数据
public static string HttpGet(string url, string encoding)
{
string result = string.Empty;
try
{
Encoding encode = System.Text.Encoding.GetEncoding(encoding); //设置编码
//获取HttpWebRequest对象
HttpWebRequest wbRequest = (HttpWebRequest)WebRequest.Create(url);
wbRequest.Method = "GET";
//设置用户代理
wbRequest.UserAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.84 Safari/537.36";
//获取返回流
HttpWebResponse wbResponse = (HttpWebResponse)wbRequest.GetResponse();
using (Stream responseStream = wbResponse.GetResponseStream())
{
//读取返回流
using (StreamReader sReader = new StreamReader(responseStream, encode))
{
result = sReader.ReadToEnd();
}
}
}
catch (Exception ex)
{
Console.WriteLine("error");
}
return result;
}
2 通过WebClient获取网页数据
static string HttpGet(string url, string encoding)
{
Encoding encode = System.Text.Encoding.GetEncoding(encoding);
WebClient MyWebClient = new WebClient();
MyWebClient.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.84 Safari/537.36");
MyWebClient.Credentials = CredentialCache.DefaultCredentials;//获取或设置用于向Internet资源的请求进行身份验证的网络凭据
Byte[] pageData = MyWebClient.DownloadData("http://www.net.cn/static/customercare/yourip.asp"); //从指定网站下载数据
string pageHtml = encode.GetString(pageData); //如果获取网站页面采用的是GB2312,则 使用这句
return pageHtml;
}
未知的原因HttpWebRequest用正则解析不挣钱,只好使用HttpWebRequest
3 使用正则表达式获取ip地址
public static string parseHtml(String pageHtml)
{
string ip = "";
Match m = Regex.Match(pageHtml, @"\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}");
if (m.Success)
{
MessageBox.Show(m.Value);
}
ip = pageHtml;
return ip;
}
测试
var a = HttpGet("http://www.ip138.com", "gbk");
var b = HttpGet("https://www.ip.cn", "utf-8");
var c = HttpGet("http://www.ip138.com/ips138.asp", "gbk");
var d = HttpGet("http://www.net.cn/static/customercare/yourip.asp", "gbk");
var a1=parseHtml(a);
var b1= parseHtml(b);
var c1=parseHtml(c);
var d1=parseHtml(d);
学习知识:
WebClient类提供向 URI 标识的资源发送数据和从 URI 标识的资源接收数据的公共方法。 其实就相当于创建一个请求客户端。可以获取网页和各种各样的信息,包括交互。
WebClient不能处理特定于任何协议的任何特性,例如Cookie等。如果需要使用这些特性,需要使用.net中的HttpWebRequest类。
System.Web.HttpRequest是封装浏览器对服务器的请求的,主要用在ASP.NET中,其中包括浏览器请求的网址,查询字符串数据或表单数据等等
需要设置用户代理,不然无法访问。
{n,m} | m和n均为非负整数,其中n<=m。最少匹配n次且最多匹配m次。例如,“o{1,3}”将匹配“fooooood”中的前三个o。“o{0,1}”等价于“o?”。请注意在逗号和两个数之间不能有空格。 |
\d | 匹配一个数字字符。等价于[0-9]。 |
所以 \d{1,3}.就是匹配3个数字字符 比如 :192.168.102 匹配192.
最开始正则表达式是 \d{1,3}.\d{1,3}.\d{1,3}.\d{1,3} 结果 2>118.116.117.220
发现 有2> 是<h2>上面的标签 ,去掉2>,也就是去掉数字加上‘>’标签
查阅正则表达式规则 发现:
(?!pattern) | 正向否定预查,在任何不匹配pattern的字符串开始处匹配查找字符串。这是一个非获取匹配,也就是说,该匹配不需要获取供以后使用。例如“Windows(?!95|98|NT|2000)”能匹配“Windows3.1”中的“Windows”,但不能匹配“Windows2000”中的“Windows”。 |
改为 (?!\d>)\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3} 结果:118.116.117.220