python爬虫学习第四章

html,body,div,span,applet,object,iframe,h1,h2,h3,h4,h5,h6,p,blockquote,pre,a,abbr,acronym,address,big,cite,code,del,dfn,em,img,ins,kbd,q,s,samp,small,strike,strong,sub,sup,tt,var,b,u,i,center,dl,dt,dd,ol,ul,li,fieldset,form,label,legend,table,caption,tbody,tfoot,thead,tr,th,td,article,aside,canvas,details,embed,figure,figcaption,footer,header,hgroup,menu,nav,output,ruby,section,summary,time,mark,audio,video { margin: 0; padding: 0; border: 0 }
body { font-family: Helvetica, arial, freesans, clean, sans-serif; font-size: 14px; line-height: 1.6; color: #333; background-color: #fff; padding: 20px; max-width: 960px; margin: 0 auto }
body>*:first-child { margin-top: 0 !important }
body>*:last-child { margin-bottom: 0 !important }
p,blockquote,ul,ol,dl,table,pre { margin: 15px 0 }
h1,h2,h3,h4,h5,h6 { margin: 20px 0 10px; padding: 0; font-weight: bold }
h1 tt,h1 code,h2 tt,h2 code,h3 tt,h3 code,h4 tt,h4 code,h5 tt,h5 code,h6 tt,h6 code { font-size: inherit }
h1 { font-size: 28px; color: #000 }
h2 { font-size: 24px; border-bottom: 1px solid #ccc; color: #000 }
h3 { font-size: 18px }
h4 { font-size: 16px }
h5 { font-size: 14px }
h6 { color: #777; font-size: 14px }
body>h2:first-child,body>h1:first-child,body>h1:first-child+h2,body>h3:first-child,body>h4:first-child,body>h5:first-child,body>h6:first-child { margin-top: 0; padding-top: 0 }
a:first-child h1,a:first-child h2,a:first-child h3,a:first-child h4,a:first-child h5,a:first-child h6 { margin-top: 0; padding-top: 0 }
h1+p,h2+p,h3+p,h4+p,h5+p,h6+p { margin-top: 10px }
a { color: #4183C4; text-decoration: none }
a:hover { text-decoration: underline }
ul,ol { padding-left: 30px }
ul li>:first-child,ol li>:first-child,ul li ul:first-of-type,ol li ol:first-of-type,ul li ol:first-of-type,ol li ul:first-of-type { margin-top: 0px }
ul ul,ul ol,ol ol,ol ul { margin-bottom: 0 }
dl { padding: 0 }
dl dt { font-size: 14px; font-weight: bold; font-style: italic; padding: 0; margin: 15px 0 5px }
dl dt:first-child { padding: 0 }
dl dt>:first-child { margin-top: 0px }
dl dt>:last-child { margin-bottom: 0px }
dl dd { margin: 0 0 15px; padding: 0 15px }
dl dd>:first-child { margin-top: 0px }
dl dd>:last-child { margin-bottom: 0px }
pre,code,tt { font-size: 12px; font-family: Consolas, "Liberation Mono", Courier, monospace }
code,tt { margin: 0 0px; padding: 0px 0px; white-space: nowrap; border: 1px solid #eaeaea; background-color: #f8f8f8 }
pre>code { margin: 0; padding: 0; white-space: pre; border: none; background: transparent }
pre { background-color: #f8f8f8; border: 1px solid #ccc; font-size: 13px; line-height: 19px; overflow: auto; padding: 6px 10px }
pre code,pre tt { background-color: transparent; border: none }
kbd { background-color: #DDDDDD; background-image: linear-gradient(#F1F1F1, #DDDDDD); background-repeat: repeat-x; border-color: #DDDDDD #CCCCCC #CCCCCC #DDDDDD; border-style: solid; border-width: 1px; font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; line-height: 10px; padding: 1px 4px }
blockquote { border-left: 4px solid #DDD; padding: 0 15px; color: #777 }
blockquote>:first-child { margin-top: 0px }
blockquote>:last-child { margin-bottom: 0px }
hr { clear: both; margin: 15px 0; height: 0px; overflow: hidden; border: none; background: transparent; border-bottom: 4px solid #ddd; padding: 0 }
table th { font-weight: bold }
table th,table td { border: 1px solid #ccc; padding: 6px 13px }
table tr { border-top: 1px solid #ccc; background-color: #fff }
table tr:nth-child(2n) { background-color: #f8f8f8 }
img { max-width: 100% }

Urllib库与URLError异常处理

什么是Urllib库

Urllib是Python提供的一个用于操作URL的模块。

快速使用Urllib爬取网页

首先导入模块
import urllib.request
导入后,爬取
file = urllib.request.urlopen("http://www.baidu.com")
读取,三种方式
1. file.read()读取文件的全部内容,与readlines不同的是,read会把读取到的内容赋给一个字符串变量
2. file.readlines()读取文件的全部内容,与read不同的是,readlines会把读取到的内容赋给一个列表变量,若要读取全部内容,推荐使用这种方式
3. File.readline()读取文件的一行文件。
如何将爬取到的网页保存到本地以网页形式
1. 首先,爬取一个网页并将爬取到的内容赋值给一个变量。
2. 以写入的方式打开一个本地文件,命名为*.html等网络格式。
3. 将1中变量写入文件
4. 关闭该文件。
fhandle=open(r"C:\Users\My\Desktop\git学习\1.html",‘wb‘)
fhandle.write(file.read())
fhandle.close()

urlretreve()函数

直接将对应信息写入文件。格式:urllib.request.urlretrieve(url,filename=本地文件地址)

urllib.request.urlretrieve("http://www.51cto.com/",filename=r"C:\Users\My\Desktop\git学习\2.html")
urlretrieve执行的过程中,会产生缓存,清除缓存
urllib.request.urlcleanup()
获取与当前环境相关的信息使用info。file.info()
获取当前爬取网页的状态码,使用getcode(),若返回200为正确,返回其他的不正确。
file.getcode()
获取爬取网页的URL,使用geturl()file.geturl()
一般来说,URL标准中只会允许一部分ASCII字符比如数字、字母、部分符号等,而其他的一些字符,比如汉字等,是不符合URL标准的。所以如果我们在URL中使用一些其他不符合标准的字符就会出现问题,此时需要进行URL编码方可解决。比如在URL中输入中文或者“:”或者“&”等不符合标准的字符时,需要编码。
如果要进行编码,使用urllib.request.quete()进行,比如,我们对“http://www.sina.com.cn"进行编码。
urllib.reqeust.quote("http://www.sina.com.cn")
输出‘http%3A//www.sina.com.cn‘

解码
urllib.request.unquote("http%3A//www.sina.com.cn")
输出‘http://www.sina.com.cn‘

浏览器的模拟---Headers属性

有时候,我们无法爬取一些网页,出现403错误,这是因为这些网页为了防止别人恶意采集信息进行的反爬虫的设置。
如果想爬取,我们可以设置Headers信息,模拟成浏览器去访问这些网站。设置Headers,首先需要的是找出User-Agent。

有两种方法让爬虫模拟成浏览器范文网页
1. 使用buildopener()修改报头
import urllib.request
url="网页地址"
headers=("User-Agent","浏览器里找到的User-Agent")
opener=urllib.request.build_opener()
opener.addheaders=[headers]
data=opener.open(url).read()
fhandler=open("存放网页的地址","wb")
fhandler.write(data)
fhandler.close()

2. 使用add
header()添加报头
import urllib.request
url="网页地址"
req=urllib.request.Request(url)
req.add_header(‘User-Agent‘,"浏览器找到的User-Agent")
data=urllib.request.urlopen(req).read()

超时设置

有的时候,访问一个网页,如果该网页长时间未响应,那么系统判断该网页超时,即无法打开该网页。
import urllib.requestfile=urllib.request.urlopen("网页地址",timeout=时间值)

HTTP协议请求实战

HTTP协议请求主要分为6种类型。
1. GET请求:GET请求会通过URL网址传递信息,可以直接在URL中写上要传递的信息,也可以有表单进行传递。如果使用表单进行传递,这表单中的信息会自动转为URL地址中的数据,通过URL地址传递。
2. POST请求:可以向服务器提交数据,是一种比较主流也比较安全的数据传递方式,比如在登录时,经常使用POST请求发送数据。
3. PUT请求:请求服务器存储一个资源,通常要指定存储的位置。
4. DELETE请求:请求服务器删除一个资源
5. HEAD请求:请求获取对应的HTTP报头信息。
6. OPTIONS请求:可以获得当前URL所支持的请求类型。
除此之外还有TRACE请求和CONNECT请求等,TRACE请求主要用于测试或诊断。
详细讲解GET与POST
- GET请求实例分析
import urllib.request
keywd="hello"
url="http://www.baidu.com/s?wd="+keywd
req=urllib.request.Request(url)
data=urllib.request.urlopen(req).read()
fhandle=open("文件存储地址","wb")
fhandle=write(data)
fhandle.close()

当检索中文会报错。
UnicodeEncodeError
import urllib.request
url="http://www.baidu.com/s?wd="
key="韦玮老师"
key_code=urllib.request.quote(key)
url_all=url+key_code
req=urllib.request.Request(url_all)
data=urllib.request.urlopen(req).read()
fh=open("文件地址","wb")
fh.write(data)
fh.close()

使用GET请求,思路如下:
1. 构建对应的URL地址,该URL地址包含GET请求的字段名和字段内容等信息,并且URL地址满足GET请求的格式,即“http://网址?字段名1=字段内容1&字段名2=字段内容2”。
2. 对应的URL为参数,构建Request对象。
3. 通过urlopen()打开构建的Request对象。
4. 按需求进行后续的处理操作。比如读取网页内容,或写入文件。
- POST请求实例分析
使用Post请求,思路如下: 1. 设置好URL网址。
2. 构建表单数据,并使用urllib.parse.urlencode对数据进行编码处理
3. 创建Request对象,参数包括URL地址和要传递的数据。
4. 使用add_header()添加头信息,模拟浏览器进行爬取。
5. 使用urllib.request.urlopen()打开对应的Request对象,完成信息的传递。
6. 后续处理,比如读取,写入文件等。
import urllib.request
import urllib.parse
url="网页地址"
postdata=urllib.parse.urlencode({
‘name‘:‘aaa‘,
‘pass‘:‘bbb‘}).encode(‘utf-8‘)#将数据使用urlencode编码处理后,使用encode()设置为utf-8编码
req=urllib.request.Request(url,postdata)
req.add_header(‘User-Agent‘,‘User-Agent数据‘)
data=urllib.request.urlopen(req).read()
fd=open("存储地址",‘wb‘)
fd.write(data)
fd.close()

代理服务器的设置

#代理服务器网站http://yum.iqianyue.com/proxy
def use_proxy(proxy_addr,url):
import urllib.request
proxy=urllib.request.ProxyHandler({‘http‘:proxy_addr})
opener=urllib.request.build_opener(proxy,urllib.request.HTTPHandler)
urllib.request.install_opener(opener)
data=urllib.request.urlopen(url).read().decode(‘utf-8‘)
return data
proxy_addr="代理服务器地址加端口"
data=use_proxy(proxy_addr,"网页地址")
print(len(data))

DebugLog实战

异常处理神器----URLError实战

import urllib.request
import urllib.error
try:
urllib.request.urlopen("网页地址")
except urllib.error.URLError as e:
print(e.code)
print(e.reason)
输出错误:
403
Forbidden

产生URLError的原因有如下几种可能:1. 链接不上服务器2. 远程URL不存在3. 无网络4. 触发了HTTPError403触发了是URLError的子类HTTPError,所以可以改成import urllib.request
import urllib.error
try:
urllib.request.urlopen("网页地址")
except urllib.error.HTTPError as e:
print(e.code)
print(e.reason)
状态码含义:200 OK
一切正常
301 Moved Permanently
重定向到新的URL,永久性
302 Found
重定向到临时的URL,非永久性
304 Not Modified
请求的资源为更新
400 Bad Request
非法请求
401 Unauthorized
请求未经授权
403 Forbidden
禁止访问
404 Not Found
没有找到对应页面
500 Internal Server Error
服务器内部出现错误
501 Not Implemented
服务器不支持实现请求所需要的功能
HTTPError无法处理URLError的前三个错误。处理会报错。import urllib.request
import urllib.error
try:
urllib.request.urlopen("http://blog.baidusss.net")
except urllib.error.HTTPError as e:
print(e.code)
print(e.reason)
except urllib.error.URLError as e:
print(e.reason)

原文地址:https://www.cnblogs.com/dcotorbool/p/8279047.html

时间: 2024-07-29 14:13:57

python爬虫学习第四章的相关文章

Python爬虫学习:四、headers和data的获取

之前在学习爬虫时,偶尔会遇到一些问题是有些网站需要登录后才能爬取内容,有的网站会识别是否是由浏览器发出的请求. 一.headers的获取 就以博客园的首页为例:http://www.cnblogs.com/ 打开网页,按下F12键,如下图所示: 点击下方标签中的Network,如下: 之后再点击下图所示位置: 找到红色下划线位置所示的标签并点击,在右边的显示内容中可以查看到所需要的headers信息. 一般只需要添加User-Agent这一信息就足够了,headers同样也是字典类型: user

python爬虫学习第五章正则

html,body,div,span,applet,object,iframe,h1,h2,h3,h4,h5,h6,p,blockquote,pre,a,abbr,acronym,address,big,cite,code,del,dfn,em,img,ins,kbd,q,s,samp,small,strike,strong,sub,sup,tt,var,b,u,i,center,dl,dt,dd,ol,ul,li,fieldset,form,label,legend,table,caption

python爬虫学习第三章

html,body,div,span,applet,object,iframe,h1,h2,h3,h4,h5,h6,p,blockquote,pre,a,abbr,acronym,address,big,cite,code,del,dfn,em,img,ins,kbd,q,s,samp,small,strike,strong,sub,sup,tt,var,b,u,i,center,dl,dt,dd,ol,ul,li,fieldset,form,label,legend,table,caption

Python爬虫学习系列教程

Python爬虫学习系列教程 大家好哈,我呢最近在学习Python爬虫,感觉非常有意思,真的让生活可以方便很多.学习过程中我把一些学习的笔记总结下来,还记录了一些自己实际写的一些小爬虫,在这里跟大家一同分享,希望对Python爬虫感兴趣的童鞋有帮助,如果有机会期待与大家的交流. Python版本:2.7 一.爬虫入门 1. Python爬虫入门一之综述 2. Python爬虫入门二之爬虫基础了解 3. Python爬虫入门三之Urllib库的基本使用 4. Python爬虫入门四之Urllib库

Python爬虫学习路线,强烈建议收藏这十一条

(一)如何学习Python 学习Python大致可以分为以下几个阶段: 1.刚上手的时候肯定是先过一遍Python最基本的知识,比如说:变量.数据结构.语法等,基础过的很快,基本上1~2周时间就能过完了,我当时是在这儿看的基础:Python 简介 | 菜鸟教程 2.看完基础后,就是做一些小项目巩固基础,比方说:做一个终端计算器,如果实在找不到什么练手项目,可以在 Codecademy - learn to code, interactively, for free 上面进行练习. 如果时间充裕的

Python爬虫学习:三、爬虫的基本操作流程

本文是博主原创随笔,转载时请注明出处Maple2cat|Python爬虫学习:三.爬虫的基本操作与流程 一般我们使用Python爬虫都是希望实现一套完整的功能,如下: 1.爬虫目标数据.信息: 2.将数据或信息存入数据库中: 3.数据展示,即在Web端进行显示,并有自己的分析说明. 这次我先介绍第一个功能中所需要实现的基本操作: 爬虫的基本操作:      表示必须步骤           表示可选步骤 导入爬虫所需要的库(如:urllib.urllib2.BeautifulSoup.Scrap

2018/7/21 Python 爬虫学习

2018/7/21,这几天整理出来的一些Python 爬虫学习代码. import urllib2 response = urllib2.urlopen("http://baidu.com") html = response.read() print html 进一步,可以request import urllib2 req = urllib2.Request("http://www.baidu.com") response = urllib2.urlopen(re

Python实战:Python爬虫学习教程,获取电影排行榜

Python应用现在如火如荼,应用范围很广.因其效率高开发迅速的优势,快速进入编程语言排行榜前几名.本系列文章致力于可以全面系统的介绍Python语言开发知识和相关知识总结.希望大家能够快速入门并学习Python这门语言. 本文是在前一部分Python基础之上程序员带你十天快速入门Python,玩转电脑软件开发(四),再次进行的Python爬虫实战课程. 正则表达式实例简单详解 正则表达式干什么用? 就是在字符串中提取我们需要的内容的. 记得哦,要先引用正则表达式模块的哦. re就是正则表达式相

《Python爬虫学习系列教程》学习笔记

转自:http://cuiqingcai.com/1052.html 大家好哈,我呢最近在学习Python爬虫,感觉非常有意思,真的让生活可以方便很多.学习过程中我把一些学习的笔记总结下来,还记录了一些自己实际写的一些小爬虫,在这里跟大家一同分享,希望对Python爬虫感兴趣的童鞋有帮助,如果有机会期待与大家的交流. 一.Python入门 1. Python爬虫入门一之综述 2. Python爬虫入门二之爬虫基础了解 3. Python爬虫入门三之Urllib库的基本使用 4. Python爬虫