第一篇随笔:用VB.NET搞点简单事情(1)
2024-08-31 08:23:13
网络上能搜索到的爬虫文章大多是用python做的,也有少部分是C#做的(小声:所以用VB.NET也可以做爬虫.本文写的是第一步:获取网页)
使用代码前先imports以下内容
Imports System.IO, System.IO.Compression, System.Text, System.Net
写程序前先开浏览器(我用的Chrome),随便上个网页,F12看下header,粘下来useragent备用,也可以粘下accept,cookie等(在本文中用不到
用httpwebrequest建立请求,用httpwebresponse得到响应体.然后考虑下压缩的问题(imports System.IO.Compression就是解决这个的)
最后得到真正的返回流,streamreader读取之,然后网页的http代码就搞下来了.用这种方法可以搞定编码为UTF-8的网页对于编码是GB2312或GBK的需有改动:使用streamreader时第二个参数改为Encoding.GetEncoding("gbk")
下面是代码:
Public Function GetHttpContent(url As String) As String
Try
Dim req As HttpWebRequest = HttpWebRequest.CreateHttp(url), resp As HttpWebResponse, sol$
With req
.UserAgent = "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36"
.Accept = "*/*"
.Method = "GET"
.Timeout =
.Headers.Add("accept-encoding", " gzip, deflate")
End With
resp = req.GetResponse
Select Case resp.ContentEncoding.ToLower
Case "gzip"
Using z As New GZipStream(resp.GetResponseStream, CompressionMode.Decompress)
Using sr As New StreamReader(z, Encoding.UTF8)
sol = sr.ReadToEnd
End Using
End Using
Exit Select
Case "deflate"
Using z As New DeflateStream(resp.GetResponseStream, CompressionMode.Decompress)
Using sr As New StreamReader(z, Encoding.UTF8)
sol = sr.ReadToEnd
End Using
End Using
Exit Select
Case Else
Using sr As New StreamReader(resp.GetResponseStream, Encoding.UTF8)
sol = sr.ReadToEnd
End Using
Exit Select
End Select
Return sol
Catch ex As Exception
Return ""
End Try
End Function
(本人水平有限,代码有不完善的地方欢迎指出
最新文章
- ztree-demo 2
- 你写的Try...Catch真的有必要么?
- MS SQL 排序规则总结
- Openjudge 1.13.37:乒乓球
- linux 进程的创建
- hadoop常见错误集锦
- solr 高亮配置
- 3G 2G GPRS 1G的概念
- Team Foundation Server 2013 with Update 3 Install LOG
- 素数与素性测试(Miller-Rabin测试)
- USACO Cow Pedigrees 【Dp】
- VCL改变主窗体的方法
- Android中那些有你不知道的事
- Linux.杀毒.Centos安装杀毒软件Clam
- java实习面试题(阿里一面)
- 分布式存储ceph——(4)ceph 添加/删除osd
- 【python-appium】模拟手机按键搜索异常
- LDAP2-创建OU创建用户
- nlog 的手动配置
- redis水平扩展实践,完全配置,无需代码改动