怎么用python爬网站_Python爬虫入门 怎么用python扒网页?

0.jpeg

640.jpeg

python爬虫网页的基本流程:首先选取一部分精心挑选的种子URL。

将这些URL放入待抓取URL队列。

从待抓取URL队列中读取待抓取队列的URL,解析DNS,并且得到主机的IP,并将URL对应的网页下载下来,存储进已下载网页库中。此外,将这些URL放进已抓取URL队列。

分析已抓取URL队列中的URL,从已下载的网页数据中分析出其他URL,并和已抓取的URL进行比较去重,最后将去重过的URL放入待抓取URL队列,从而进入下一个循环。

1、HTTP请求实现

使用urllib2/urllib实现:

urllib2和urllib是Python中的两个内置模块,要实现HTTP功能,实现方式是以urllib2为主,urllib为辅。

urllib2提供一个基础函数urlopen,通过向指定的URL发出请求来获取数据。最简单的形式是:import urllib2response=urllib2.urlopen("http://www.zhihu.com")html=response.read()print html

其实可以将上面对http://www.zhihu.com的请求响应分为两步,一步是请求,一步是响应,形式如下:import urllib2# 请求request=urllib2.Request("http://www.zhihu.com")# 响应response = urllib2.urlopen(request)html=response.read()print html

还有post请求实现:import urllibimport urllib2url = "http://www.xxxxxx.com/login"postdata = {"username" : "qiye","password" : "qiye_pass"}# info 需要被编码为urllib2能理解的格式,这里用到的是urllibdata = urllib.urlencode(postdata)req = urllib2.Request(url, data)response = urllib2.urlopen(req)html = response.read()

将上面的例子改写一下,加上请求头信息,设置一下请求头中的User-Agent域和Referer域信息。2、请求头headers处理import urllibimport urllib2url = "http://www.xxxxxx.com/login"user_agent = "Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)"referer="http://www.xxxxxx.com/"postdata = {"username" : "qiye","password" : "qiye_pass"}# 将user_agent,referer写入头信息headers={"User-Agent":user_agent,"Referer":referer}data = urllib.urlencode(postdata)req = urllib2.Request(url, data,headers)response = urllib2.urlopen(req)html = response.read()

urllib2对Cookie的处理也是自动的,使用CookieJar函数进行Cookie的管理。如果需要得到某个Cookie项的值,可以这么做:3、Cookie处理import urllib2import cookielibcookie = cookielib.CookieJar()opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie))response = opener.open("http://www.zhihu.com")for item in cookie:print item.name+":"+item.value

但是有时候会遇到这种情况,我们不想让urllib2自动处理,我们想自己添加Cookie的内容,可以通过设置请求头import urllib2opener = urllib2.build_opener()opener.addheaders.append( ( "Cookie", "email=" + "xxxxxxx@163.com" ) )req = urllib2.Request( "http://www.zhihu.com/" )response = opener.open(req)print response.headersretdata = response.read()

640.png

欢迎大家点赞,留言,转发,转载,感谢大家的相伴与支持

万水千山总是情,点个【在看】行不行

*声明:本文于网络整理,版权归原作者所有,如来源信息有误或侵犯权益,请联系我们删除或授权事宜

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值