赞
踩
使用 Python 内置的 urllib 库获取网页的 html 信息。注意,urllib 库属于 Python 的标准库模块,无须单独安装,它是 Python 爬虫的常用模块
向百度(百度一下,你就知道)发起请求,获取百度首页的 HTML 信息
- #导包,发起请求使用urllib库的request请求模块
- import urllib.request
- # urlopen()向URL发请求,返回响应对象,注意url必须完整
- response=urllib.request.urlopen('http://www.baidu.com/')
- print(response)
上述代码会返回百度首页的响应对象, 其中 urlopen() 表示打开一个网页地址。注意:请求的 url 必须带有 http 或者 https 传输协议
运行结果:
<http.client.HTTPResponse object at 0x000001F71D8A6220>
也有另外一种导包方式,也就是使用 from
- #发起请求使用urllib库的request请求模块
- from urllib import request
- response=request.urlopen('http://www.baidu.com/')
- print(response)
- # 导包,发起请求使用urllib库的request请求模块
- import urllib.request
- # urlopen()向URL发请求,返回响应对象,注意url必须完整
- response=urllib.request.urlopen('http://www.baidu.com/')
- # 提取响应内容
- html=response.read().decode('utf-8')
- print(html)
运行结果:
<!DOCTYPE html><!--STATUS OK--> <html><head><meta http-equiv="Content-Type" content="text/html;charset=utf-8"><meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"><meta content="always" name="referrer"><meta name="theme-color" content="#2932e1"><meta name="description" content="全球最大的中文搜索引擎、致力于让网民更便捷地获取信息,找到...">...</html>
通过调用 response 响应对象的 read() 方法提取 HTML 信息,该方法返回的结果是字节串类型(bytes),因此需要使用 decode() 转换为字符串
urllib库的常用方法
表示向网站发起请求并获取响应对象
urllib.request.urlopen(url,timeout)
该方法用于创建请求对象、包装请求头,比如重构 User-Agent(即用户代理,指用户使用的浏览器)使程序更像人类的请求,而非机器。重构 User-Agent 是爬虫和反爬虫斗争的第一步
urllib.request.Request(url,headers)
- bytes = response.read() # read()返回结果为 bytes 数据类型
- string = response.read().decode() # decode()将字节串转换为 string 类型
- url = response.geturl() # 返回响应对象的URL地址
- code = response.getcode() # 返回请求时的HTTP响应码
- #字符串转换为字节码
- string.encode("utf-8")
- #字节码转换为字符串
- bytes.decode("utf-8")
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。