python3 urllib

1.基本方法

urllib.request.urlopen(urldata=None[timeout]*cafile=Nonecapath=Nonecadefault=Falsecontext=None)

-         url:  须要打开的网址python

-         data:Post提交的数据json

-         timeout:设置网站的访问超时时间浏览器

直接用urllib.request模块的urlopen()获取页面,page的数据格式为bytes类型,须要decode()解码,转换成str类型。服务器

from urllib import request
response = request.urlopen(r'http://www.baidu.com/') 
page = response.read()
page = page.decode('utf-8')
print(page)

urlopen返回对象所提供方法:网站

-         read() , readline() ,readlines() , fileno() , close() :对HTTPResponse类型数据进行操做编码

-         info():返回HTTPMessage对象,表示远程服务器返回的头信息url

-         getcode():返回Http状态码。若是是http请求,200请求成功完成;404网址未找到spa

-         geturl():返回请求的url操作系统

 

2.使用Request

urllib.request.Request(url, data=None, headers={}, method=None)

使用request()来包装请求,再经过urlopen()获取页面。code

from urllib import request

url = r'http://www.lagou.com/zhaopin/Python/?labelWords=label'
headers = {
    'User-Agent': r'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) '
                  r'Chrome/45.0.2454.85 Safari/537.36 115Browser/6.0.3',
    'Referer': r'http://www.lagou.com/zhaopin/Python/?labelWords=label',
    'Connection': 'keep-alive'
}
req = request.Request(url, headers=headers)
page = request.urlopen(req).read()
page = page.decode('utf-8')
print(page)

通过urlencode()转换后的data数据为?first=true?pn=1?kd=Python,最后提交的url为

http://www.lagou.com/jobs/positionAjax.json?first=true?pn=1?kd=Python

Post的数据必须是bytes或者iterable of bytes,不能是str,所以须要进行encode()编码

用来包装头部的数据:

-         User-Agent :这个头部能够携带以下几条信息:浏览器名和版本号、操做系统名和版本号、默认语言

-         Referer:能够用来防止盗链,有一些网站图片显示来源http://***.com,就是检查Referer来鉴定的

-         Connection:表示链接状态,记录Session的状态。

3.Post数据

urllib.request.urlopen(urldata=None[timeout]*cafile=Nonecapath=Nonecadefault=Falsecontext=None)

urlopen()的data参数默认为None,当data参数不为空的时候,urlopen()提交方式为Post。

from urllib import request, parse

url = r'http://www.lagou.com/jobs/positionAjax.json?'
headers = {
    'User-Agent': r'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) '
                  r'Chrome/45.0.2454.85 Safari/537.36 115Browser/6.0.3',
    'Referer': r'http://www.lagou.com/zhaopin/Python/?labelWords=label',
    'Connection': 'keep-alive'
}
data = {
    'first': 'true',
    'pn': 1,
    'kd': 'Python'
}
data = parse.urlencode(data).encode('utf-8')
req = request.Request(url, headers=headers, data=data)
page = request.urlopen(req).read()
page = page.decode('utf-8')
print(page)

urllib.parse.urlencode(query, doseq=False, safe='', encoding=None, errors=None)

urlencode()主要做用就是将url附上要提交的数据。 

通过urlencode()转换后的data数据为?first=true?pn=1?kd=Python,最后提交的url为

http://www.lagou.com/jobs/positionAjax.json?first=true?pn=1?kd=Python

Post的数据必须是bytes或者iterable of bytes,不能是str,所以须要进行encode()编码

 

 

注:此篇文章写的更详细些:

https://yq.aliyun.com/ziliao/109346 

相关文章
相关标签/搜索