美文网首页
Python 爬虫笔记2一(编码转码urlencode与unqu

Python 爬虫笔记2一(编码转码urlencode与unqu

作者: dinglangping | 来源:发表于2018-03-23 18:06 被阅读0次

当url地址含有中文或者“/”的时候,这是就需要用做urlencode一下编码转换。

一、urlencode

urlencode的参数是词典,它可以将key-value这样的键值对转换成我们想要的格式。如果你用的是python2.*,urlencode在urllib.urlencode。如果使用的是python3,urlencode在urllib.parse.urlencode

例如

[python] view plain copy

import urllib.parse  

data={"name":"王尼玛","age":"/","addr":"abcdef"}  

print(urllib.parse.urlencode(data))  

输出为

[python] view plain copy

addr=abcdef&name=%E7%8E%8B%E5%B0%BC%E7%8E%9B&age=%2F  

如果只想对一个字符串进行urlencode转换,怎么办?urllib提供另外一个函数:quote()

[python] view plain copy

print(urllib.parse.quote("hahaha你好啊!"))  

输出为

[python] view plain copy

hahaha%E4%BD%A0%E5%A5%BD%E5%95%8A%EF%BC%81  

二、unquote

当urlencode之后的字符串传递过来之后,接受完毕就要解码了——urldecode。urllib提供了unquote()这个函数,可没有urldecode()!

[python] view plain copy

import  urllib.parse  

data={"name":"王尼玛","age":"/","addr":"abcdef"}  

print(urllib.parse.urlencode(data))  

print(urllib.parse.quote("hahaha你好啊!"))  

print(urllib.parse.unquote("hahaha%E4%BD%A0%E5%A5%BD%E5%95%8A%EF%BC%81"))  

输出

[python] view plain copy

addr=abcdef&name=%E7%8E%8B%E5%B0%BC%E7%8E%9B&age=%2F  

hahaha%E4%BD%A0%E5%A5%BD%E5%95%8A%EF%BC%81  

hahaha你好啊!  

在做urldecode的时候,看unquote()这个函数的输出,是对应中文在gbk下的编码,在对比一下quote()的结果不难发现,所谓的urlencode就是把字符串转车gbk编码,然后把\x替换成%。如果你的终端是utf8编码的,那么要把结果再转成utf8输出,否则就乱码。

可以根据实际情况,自定义或者重写urlencode()、urldecode()等函数。

三、小例子

如果要抓取百度上面搜索关键词为“王尼玛的体重”的网页, 则代码如下

[python] view plain copy

import urllib  

import urllib.request  

data={}  

data['word']="王尼玛的体重"  

url_values=urllib.parse.urlencode(data)  

url="http://www.baidu.com/s?"  

full_url=url+url_values  

data=urllib.request.urlopen(full_url).read()  

data=data.decode('UTF-8')  

print(data)  

相关文章

网友评论

      本文标题:Python 爬虫笔记2一(编码转码urlencode与unqu

      本文链接:https://www.haomeiwen.com/subject/otgxcftx.html