python3中urllib中包括了四个模块,包括:
urllib.request urllib.error urllib.parse urllib.robotparser
urllib.request可以用来发送request和获取request的结果
urllib.error包含了urllib.request产生的异常
urllib.parse用来解析和处理URLurllib.robotparse用来解析页面的robots.txt文件
urllib.request.urlopen()基本使用
1、urllib.request 模块提供了最基本的构造 HTTP 请求的方法,利用它可以模拟浏览器的一个请求发起过程,同时它还带有处理 authenticaton (授权验证), redirections (重定向), cookies (浏览器Cookies)以及其它内容。
class urllib.request.Request(url, data=None, headers={}, origin_req_host=None, unverifiable=False, method=None)
第一个参数url用于请求URL,这是必传参数,其他都是可选参数。
第二个参数data如果要传,必须传bytes(字节流)类型的。如果它是字典,可以先用urllib.parse模块里的urlencode()编码。
第三个参数headers是一个字典,它就是请求头,我们可以在构造请求时通过headers参数直接构造,也可以通过调用请求实例的add_header()方法添加。
例如爬取百度https://www.baidu.com
import urllib.request # 调用urllib.request库
response = urllib.request.urlopen("https://www.baidu.com") # 将获取的源代码保存在response中
print(response.read().decode("utf-8")) # 打印response
结果
<html>
<head>
<script>
location.replace(location.href.replace("https://","http://"));
</script>
</head>
<body>
<noscript><meta http-equiv="refresh" content="0;url=http://www.baidu.com/"></noscript>
</body>
</html>
Process finished with exit code 0
注意问题
1.urllib.request ——url的request模块可以非常方便的抓取url内容,即发送一个get请求到指定的页面,然后返回HTTP的响应。
2.python爬取的数据类型可能是字符串str、二进制bytes…
①如果爬取回来的数据是bytes类型,但如果写入的时候需要字符串类型 ,则需要对其进行解码:decode(“utf-8”)
②如果爬取回来的数据是str类型,但如果写入的时候需要bytes类型,则需要对其进行编码: encode(“utf-8”)