网络上能搜索到的爬虫文章大多是用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

(本人水平有限,代码有不完善的地方欢迎指出

最新文章

  1. ztree-demo 2
  2. 你写的Try...Catch真的有必要么?
  3. MS SQL 排序规则总结
  4. Openjudge 1.13.37:乒乓球
  5. linux 进程的创建
  6. hadoop常见错误集锦
  7. solr 高亮配置
  8. 3G 2G GPRS 1G的概念
  9. Team Foundation Server 2013 with Update 3 Install LOG
  10. 素数与素性测试(Miller-Rabin测试)
  11. USACO Cow Pedigrees 【Dp】
  12. VCL改变主窗体的方法
  13. Android中那些有你不知道的事
  14. Linux.杀毒.Centos安装杀毒软件Clam
  15. java实习面试题(阿里一面)
  16. 分布式存储ceph——(4)ceph 添加/删除osd
  17. 【python-appium】模拟手机按键搜索异常
  18. LDAP2-创建OU创建用户
  19. nlog 的手动配置
  20. redis水平扩展实践,完全配置,无需代码改动

热门文章

  1. go 利用chan的阻塞机制,实现协程的开始、阻塞、返回控制器
  2. layui2.5 开关在confirm确认了之后在关/开
  3. 【红宝书】第20章.JSON
  4. weui实现滚动加载的效果
  5. IT兄弟连 HTML5教程 CSS3属性特效 CSS3背景
  6. 一泡尿的时间,快速读懂QUIC协议
  7. day 26-1 property、绑定与非绑定方法
  8. Python的输入输出的应用
  9. 性能调优 -- TPS&QPS
  10. Delphi 调用C# 编写的DLL方法