1.使用urllib库
urllib库是python内置的HTTP请求库,包含4个模块:
1.request:是最基本的http请求模块,可以用来模拟发送请求,就像在浏览器里输入网址按回车一样,只需要给库方法传入URL和其他参数,就可以实现这个过程了。
2.error:异常处理模块。
3.parse:一个工具模块,提供许多URL处理方法,比如拆分,解析,合并等。
4.robotparser:主要用来识别网站的robot.txt文件,然后判断哪些网站可以爬,它用的比较少。
1.发送请求
1.urlopen()方法
使用urlopen()方法模拟浏览器发送请求,以python官网为例:
# -*- coding: utf-8 -*-
import urllib.request
response=urllib.request.urlopen('http://www.python.org')
#爬取python官网
print(response.read().decode('utf-8'))
print(type(response))
用type()方法查看输出类型,是一个HTTPResponse类型的对象,主要包含read(),readinto(),getheader(name),getheader(),fileno(