300字范文,内容丰富有趣,生活中的好帮手!
300字范文 > python爬虫urllib 数据处理_Python 爬虫笔记之Urllib的用法

python爬虫urllib 数据处理_Python 爬虫笔记之Urllib的用法

时间:2023-01-18 09:18:30

相关推荐

python爬虫urllib 数据处理_Python 爬虫笔记之Urllib的用法

urllib总共有四个子模块,分别为request,error,parse,robotparser

request用于发送request(请求)和取得response(回应)

error包含request的异常,通常用于捕获异常

parse用于解析和处理url

robotparser用于robot.txt文件的处理

urllib.request 模块import urllib.request

response=urllib.request.urlopen("http://blog.youhaiqun.mom")

print(response.read().decode('utf-8'))

response是一个Httpresponse对象,它主要包含的方法有 read()

getheader(name),getheaders(),fileno()等函数

主要包含的属性为status,msg,reason,closed,debuglevel

可以利用response.status,或response.read()来调用并获取信息

urllib.request.urlopen()模块urllib.request.urlopen(url,data,timeout,cafile,capath,cadefault,context)

利用URLopen打开url所对应的网址,data为附加参数,其必须为bytes型,(可以利用data来进行post方式的访问)

urllib.parse.urlencode()模块urllib.parse.urlencode({'word':'hello'})

可以把字典转化为字符串

同时利用上面两个模块

data={'word':'hello'}

data=bytes(urllib.parse.urlencode(data),encoding='utf-8')

response=urllib.request.urlopen('http://blog.youhaiqun.mom',data,timeout=9)

urllib.request.Request()模块

当需要在请求中加入header时就需要用到urllib.request.Request(),urllib.request.urlopen()只能利用data来传递附加的参数

request=urllib.request.Request(url,data,headers,method='get/post')

注意: 上面并没有开始对url进行请求,只是构造了一个request,里面包含的headers,data等数据,需要经过下面的语句才算正式开始访问

response=urllib.request.urlopen(request)

print(response.read().decode('utf-8'))

也可以通过add_header()来添加headers

request=urllib.request.Request(url,data,method='POST')

request.add_header('User-Agent','Mozilla/4.0(compatible;MSIE 5.5;Windows NT)')

urllib.request.Request的高级特征

对于cookie,代理的处理`

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。