Python爬虫first day之urllib库

 urllib库的认识


1.urllib.request——请求模块



1.1 urlopen

urlopen是urllib.request模块提供的最基本的构造HTTP请求的方法,可以模拟浏览器的一个请求发起过程


1.1.1 获取一个get请求

import urllib.request
#获取一个get请求
response = urllib.request.urlopen("http://www.baidu.com")
print(response.read().decode("utf-8"))

1.1.2 获取一个post请求

import urllib.request
import urllib.parse
data = bytes(urllib.parse.urlencode({"hello":"world"}),encoding="utf-8")
response = urllib.request.urlopen("http://httpbin.org/post",data=data )
print(response.read().decode("utf-8"))
  • bytes 是一个类,调用它的构造方法,也就是 bytes(),可以将字符串按照指定的字符集转换成 bytes;如果不指定字符集,那么默认采用 UTF-8。
  • 字符串本身有一个 encode() 方法,该方法专门用来将字符串按照指定的字符集转换成对应的字节串;如果不指定字符集,那么默认采用 UTF-8。

1.1.3 data参数
data参数是可选的,并且是字节流编码格式(可以用urllib.parse.urlencode()和bytes()方法将参数转化为字节流编码格式的内容)。如果要使用data参数,则请求方式为POST


1.1.4 urlopen返回的response对象是http.client. HTTPResponse类型


1.1.5 Timeout参数

timeout参数用于设置超时,单位为秒,若不指定timeout,则使用全局默认时间。若请求超时,则会抛出urllib.error.URLError异常,可以通过try except处理异常。

import urllib.request
import urllib.error
try:
    response = urllib.request.urlopen("http://httpbin.org/get", timeout=0.01)
    print (response.read().decode("utf-8"))
except urllib.error.URLError as e:
    print("timt out!")

 2.1 request

用来传递更多的请求参数,如 url,headers,data, method
import urllib.request
import urllib.error
url = "https://www.douban.com"    
headers = {"User-Agent":" Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36 SLBrowser/7.0.0.6241 SLBChan/11"
}
req = urllib.request.Request(url=url,headers=headers)  #此处传递参数有两个
response = urllib.request.urlopen(req)      #response 接收响应
print(response.read().decode("utf-8"))

另一种方法添加headers
from urllib import request, parse
url = 'http://baidu.com/post'
dict = {
    'name': 'asd'
}
data = bytes(parse.urlencode(dict), encoding='utf8')
req = request.Request(url=url, data=data, method='POST')
req.add_header('User-Agent', 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)')
response = request.urlopen(req)
print(response.read().decode('utf-8'))

打印出响应类型,状态码等

import urllib.request
response = urllib.request.urlopen('http://www.baidu.com')
print(type(response))   #响应类型
print(response.status) # 状态码 判断请求是否成功
print(response.getheaders()) # 响应头 得到的一个元组组成的列表
print(response.getheader('Server')) #得到特定的响应头
print(response.read().decode('utf-8')) #获取响应体的内容,字节流的数据,需要转成utf-8 格式


2.urllib.error——异常处理模块

 HTTPError是URLError的子类,他的异常有3个属性:

code:返回状态码 404表示不存在,500表示服务器错误....

reason:返回错误原因

headers:返回请求头 


因为HTTPError是URLError的子类,先检查是不是HTTPError,如果不是再检查是不是URLError,如果都不是,说明请求成功

from urllib import request, error
try:
    response = request.urlopen('http://baid.com/index.htm')
except error.HTTPError as e:
    print(e.reason,'\n' ,e.code,'\n' ,e.headers,'\n' )
except error.URLError as e:
    print(e.reason)
else:
    print('Request Successfully')

第二种写法

from urllib.request import Request,urlopen
#请求某一个地址
req = Request("http://xx.baidu.com")
try:
    response = urlopen(req)
except urllib.error.URLError as e:
    if hasattr(e,'reason'):
        print("We failed to reach a server")
    elif hasattr(e,'code'):
        print("The server couldn\'t ful fill the request.")
    else:
        print("everything is fine")

hasattr判断是否拥有这个属性,如果有的话就打印,如果没有判断下一个

 try    except   用就完了


3.urllib.parse——url解析模块

URL解析功能侧重于将URL字符串拆分为其组件,或者将URL组件组合为URL字符串。

urllib.parse.urlparse(urlstring,scheme ='',allow_fragments = True )


使用 urlencode() 函数可以将一个 dict 转换成合法的查询参数:

看到特殊字符也被正确地转义了。相对的,可以使用 parse_qs() 来将查询参数解析成 dict。

from urllib.parse import urlencode
query_args = {
    'name': 'dark sun',
    'country': '中国'
}
query_args = urlencode(query_args)
print(query_args)
from urllib.parse import parse_qs
print(parse_qs(query_args))

 小记

I have to say that what I have learned today is the thing which makes my head big.At first, I felt OK. Later, I felt more and more confused and thought what happened.Today's content is not very clear and needs to be improved.

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

onlywishes

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值