Python3:urllib模块的使用
Python3:urllib模块的使用
1.基本方法
urllib.request.urlopen(url, data=None, [timeout, ]*, cafile=None, capath=None, cadefault=False, context=None)
url: 需要打开的网址
data:Post提交的数据
timeout:设置网站的访问超时时间
直接用urllib.request模块的urlopen()获取页面,page的数据格式为bytes类型,需要decode*()解码,转换成str类型。
from urllib import request
response = request.urlopen(r'http://python.org/')
page = response.read()
page = page.decode('utf-8')
urlopen返回对象提供方法: read() , readline() ,readlines() , fileno() , close() :对HTTPResponse类型数据进行操作 info():返回HTTPMessage对象,表示远程服务器返回的头信息
getcode():返回Http状态码。如果是http请求,200请求成功完成;404网址未找到
geturl():返回请求的url
2.使用Request
urllib.request.Request(url, data=None, headers={}, method=None)
使用request()来包装请求,再通过urlopen()获取页面。
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')
用来包装头部的数据:
User-Agent :这个头部可以携带如下几条信息:浏览器名和版本号、操作系统名和版本号、默认语言
Referer:可以用来防止盗链,有一些网站图片显示来源http://***.com,就是检查Referer来鉴定的
Connection:表示连接状态,记录Session的状态。
3.Post数据
urllib.request.urlopen(url, data=None, [timeout, ]*, cafile=None, capath=None, cadefault=False, context=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')
urllib.parse.urlencode(query, doseq=False, safe='', encoding=None, errors=None)
urlencode()主要作用就是将url附上要提交的数据。
data = {
'first': 'true',
'pn': 1,
'kd': 'Python'
}
data = parse.urlencode(data).encode('utf-8')
经过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()编码
当然,也可以把data的数据封装在urlopen()参数中:
page = request.urlopen(req, data=data).read()
在这里就要说点实际应用的事儿了:
从json中取出的数据类型和数据如下:
<class 'dict'> {'install': {'install_date': '2018/09/26', 'install_result': 'success'}}
经过转码:company_data = parse.urlencode(data).encode('utf-8')
变成这样:b'install=%7B%27install_date%27%3A+%272018%2F09%2F26%27%2C+%27install_result%27%3A+%27success%27%7D'
服务器端接收数据:
data = request.POST.get("company_data")
数据类型、数据分别如下:
<class 'str'> {"install": {"install_result": "success", "install_date": "2018/09/26"}}
我想要的字典变成了字符串,这就得找解决办法(用json去解决问题):
客户端:
import json
with open('1.json', 'r') as f:
data = json.load(f) data = {"company_data": json.dumps(data)} # urlopen()的data参数默认为None,当data参数不为空的时候,urlopen()提交方式为Post
from urllib import request, parse
url = r'http://192.168.165.4:8000/show/report/'
company_data = parse.urlencode(data).encode('utf-8')
req = request.Request(url, data=company_data)
print(company_data)
page = request.urlopen(req).read()
page = page.decode('utf-8')
服务器端:
@csrf_exempt
def receive_data(request):
data = request.POST.get("company_data")
if data:
try:
data = json.loads(data)
print("企业数据", type(data), data)
return HttpResponse(data)
except ValueError as e:
print(str(e))
else:
return HttpResponse("no data")
4.处理异常
from urllib import request, parse
def get_page(url):
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': ,
'kd': 'Python'
}
data = parse.urlencode(data).encode('utf-8')
req = request.Request(url, headers=headers)
try:
page = request.urlopen(req, data=data).read()
page = page.decode('utf-8')
except request.HTTPError as e:
print(e.code())
print(e.read().decode('utf-8'))
return page
get_page
5.使用代理
urllib.request.ProxyHandler(proxies=None)
当需要抓取的网站设置了访问限制,这时就需要用到代理来抓取数据。
data = {
'first': 'true',
'pn': 1,
'kd': 'Python'
}
proxy = request.ProxyHandler({'http': '5.22.195.215:80'}) # 设置proxy
opener = request.build_opener(proxy) # 挂载opener
request.install_opener(opener) # 安装opener
data = parse.urlencode(data).encode('utf-8')
page = opener.open(url, data).read()
page = page.decode('utf-8')
python3-urllib参考:https://www.cnblogs.com/Lands-ljk/p/5447127.html
Python3:urllib模块的使用的更多相关文章
- python3 urllib模块使用
urllib模块使用 urllib.request urllib.request.urlopen(url, data=None, [timeout, ]*, cafile=None, capath=N ...
- Python3学习笔记(urllib模块的使用)转http://www.cnblogs.com/Lands-ljk/p/5447127.html
Python3学习笔记(urllib模块的使用) 1.基本方法 urllib.request.urlopen(url, data=None, [timeout, ]*, cafile=None, ...
- python3 urllib和requests模块
urllib模块是python自带的,直接调用就好,用法如下: 1 #处理get请求,不传data,则为get请求 2 import urllib 3 from urllib.request impo ...
- Python3 urllib.request库的基本使用
Python3 urllib.request库的基本使用 所谓网页抓取,就是把URL地址中指定的网络资源从网络流中读取出来,保存到本地. 在Python中有很多库可以用来抓取网页,我们先学习urlli ...
- python3 urllib 类
urllib模块中的方法 1.urllib.urlopen(url[,data[,proxies]]) 打开一个url的方法,返回一个文件对象,然后可以进行类似文件对象的操作.本例试着打开google ...
- urllib模块学习
一.urllib库 概念:urllib是Python自带的一个用于爬虫的库,其主要作用就是可以通过代码模拟浏览器发送请求.其常被用到的子模块在Python3中的为urllib.request和urll ...
- 爬虫--urllib模块
一.urllib库 概念:urllib是Python自带的一个用于爬虫的库,其主要作用就是可以通过代码模拟浏览器发送请求.其常被用到的子模块在Python3中的为urllib.request和urll ...
- Python3 urllib抓取指定URL的内容
最近在研究Python,熟悉了一些基本语法和模块的使用:现在打算研究一下Python爬虫.学习主要是通过别人的博客和自己下载的一下文档进行的,自己也写一下博客作为记录学习自己过程吧.Python代码写 ...
- urllib模块的使用
Python3学习笔记(urllib模块的使用) 1.基本方法 urllib.request.urlopen(url, data=None, [timeout, ]*, cafile=None, ca ...
随机推荐
- PAT (Basic Level) Practise (中文)-1031. 查验身份证(15)
PAT (Basic Level) Practise (中文)-1031. 查验身份证(15) http://www.patest.cn/contests/pat-b-practise/1031 一个 ...
- break、continue、exit、return的区别和对比
break.continue.exit.return的区别和对比 一:说明 break.continue在条件循环语句及循环语句(for.while.if等)中用于控制程序的走向:而exit则用于种植 ...
- 条款52:写了placement new 也要写placement delete(write placement delete if you write placement new)
NOTE: 1.当你写一个placement operator new .请确定也要写出了对应的placement operator delete.如果没有这样做,你的程序可能发生隐晦而时断时续的内存 ...
- 【bug】 1118 Row size too large
1118 Row size too large Every table (regardless of storage engine) has a maximum row size of 65,535 ...
- Beautiful Soup 4.2.0 doc_tag、Name、Attributes、多值属性
找到了bs4的中文文档,对昨天爬虫程序里所涉及的bs4库进行学习.这篇代码涉及到tag.Name.Attributes以及多值属性. ''' 对象的种类 Beautiful Soup将复杂HTML文档 ...
- selenium总结(持续更新)
1.怎么 判断元素是否存在? 如果这个元素不存在, 就会抛出NoSuchElementException,可以通过使用try catch,如果catch到NoSuchElementException ...
- Python面向对象(类之间的关系)(三)
类与类之间的关系 在我们的世界中事物和事物之间总会有一些联系. 在面向对象中. 类和类之间也可以产生相关的关系 1. 依赖关系 执行某个动作的时候. 需要xxx来帮助你完成这个操作. 此时的关系是最轻 ...
- PAT Basic 1035
1035 插入与归并 根据维基百科的定义: 插入排序是迭代算法,逐一获得输入数据,逐步产生有序的输出序列.每步迭代中,算法从输入序列中取出一元素,将之插入有序序列中正确的位置.如此迭代直到全部元素有序 ...
- leetcode刷题——查找
知识点 备忘-必备算法 题目 顺序查找 二分查找 树表搜索 广度优先搜索算法(BFS) 深度优先搜索算法(DFS) 回溯(Backtracking) 题解 CS-Notes Algorithm_Int ...
- luogu3231 [HNOI2013]消毒
前置技能:poj3041 如果是二维平面有一些方块,这些方块被染了黑色,你每次可以选择 \((x,y)\) 的区域染成白色,代价是 \(\min(x,y)\),问你付出的最小代价 显然我们不会这么染 ...