爬虫基础之urllib库


categories:

  • 爬虫
    tags:
  • urlopen
  • urlretrieve
  • urlencode
  • parse_qs
  • urlparse
  • urlsplit

urllib库

urllib库是Python中一个最基本的网络请求库。可以模拟浏览器的行为,向指定的服务器发送一个请求,并可以保存服务器返回的数据

urlopen函数

在Python3的urllib库中,所有和网络请求相关的方法,都被集到 urllib.request 模块下面了,先来看下urlopen的基本使用

from urllib import request
resp = request.urlopen('http://www.baidu.com')
print(resp.read())

实际上,使用浏览器访问百度,右键查看源代码。会发现,和打印出来的数据一样。

urlopen 解释

  1. url:请求和url
  2. data:请求的data,如果设置了值,那么将变成post请求
  3. 返回值:返回一个http.client.HTTPResponse对象,这个对象是一个类文件句柄对象。有read(size)、readline、readlines以及getcode等方法
#http.client.HTTPResponse
print(resp)
<http.client.HTTPResponse object at 0x7f6466e926a0>

#read(size)
print(resp(100))
b'<html>
<meta http-equiv="refresh" content="0;url=http://www.baidu.com/">
</html>
'

#readline()
print(resp.readline())
b'<html>
'

#readlines()
print(resp.readlines())
[b'<html>
', b'<meta http-equiv="refresh" content="0;url=http://www.baidu.com/">
', b'</html>
']

#getcode()
print(resp.getcode())
200

urlretrieve函数

这个函数可以方便地将网页上一个文件保存到本地。以下代码可以非常方便地将百度的首页下载到本地

urlretrieve(下载地址,保存位置)

from urllib import request
request.urlretrieve('http://www.baidu.com','/tmp/tmp97mdqput')
#返回值 如下
('/tmp/tmp97mdqput', <http.client.HTTPMessage object at 0x7f6466e23400>)

urlencode函数

用浏览器发送请求时,如果url中包含了中文或其他特殊字符,浏览器会自动编码。如果使用代码发送请求,需手动编码,通过urlencode实现。urlencode可将字典转换为url编码格式的数据

from urllib import parse
data = {'name':'爬虫基础','greet':'hello world','age':10}
qs = parse.urlencode(data)
print(qs)
#返回值 
name=%E7%88%AC%E8%99%AB%E5%9F%BA%E7%A1%80&greet=hello+world&age=10

模拟百度查询刘德华

错误方式

from urllib import request
url = 'http://www.baidu.com/s?wd=刘德华'
qs = request.urlopen(url)
print(qs)
#在执行request.urlopen(url)时,返回报错,原因是 ascii 解压器无法对'刘德华'进行编码
UnicodeEncodeError: 'ascii' codec can't encode characters in position 7-9: ordinal not in range(128)

正确方式

from urllib import request,parse
url = 'http://www.baidu.com/s?'
param = {"wd":"刘德华"}
url_param = parse.urlencode(param)
full_url = url + url_param
print(full_url)
qs = request.urlopen(full_url)
print(qs.readline()[:100])
#返回值
b'<!DOCTYPE html>
'

parse_qs函数

可将经过编码的url参数进行解码

from urllib import parse
qs = 'name=%E7%88%AC%E8%99%AB%E5%9F%BA%E7%A1%80&greet=hello+world&age=10'
print(parse.parse_qs(qs))
#返回值
{'name': ['爬虫基础'], 'greet': ['hello world'], 'age': ['10']}

urlparse和urlsplit

有时候拿到一个url,想要对这个url进行分割,可以使用urlparse或者urlsplit

区别是urlsplit函数没有params属性

from urllib import request,parse
url = 'http://www.baidu.com/s?username=zhiliao'
#对比urlsplit,urlparse函数时,开启关闭注释
result = parse.urlsplit(url)
#result = parse.urlparse(url)

print(result)
#返回值如下
'''
urlsplit
SplitResult(scheme='http', netloc='www.baidu.com', path='/s', query='username=zhiliao', fragment='')
urlparse
ParseResult(scheme='http', netloc='www.baidu.com', path='/s', params='', query='username=zhiliao', fragment='')

'''
for i in result:
	print(i)

'''
********urlsplit*************
http
www.baidu.com
/s
username=zhiliao

**********urlparse***********
http
www.baidu.com
/s
				#此处空行对应params属性值,为''
username=zhiliao

'''

原文地址:https://www.cnblogs.com/anyux/p/12203077.html