爬虫基础笔记--爬取网页数据
使用urllib实现数据传输
传递数据的方式主要分为两种GET和POST。
GET:直接使用 URL访问,在URL中包含了所有的参数
POST:不会在URL中显示所有参数
URL编码转换
需要使用urllib.parse库中的urlencode()方法将URL进行编码
import urllib.parse
data={
'a':'黑马程序员',
# a与b 之间要用 , 分隔
'b':'hello world'
}
result=urllib.parse.urlencode(data)
print(result)
# 结果 a=%E9%BB%91%E9%A9%AC%E7%A8%8B%E5%BA%8F%E5%91%98&b=hello+world
解码使用urlparse库的unquote()方法
result2=urllib.parse.unquote('a=%E9%BB%91%E9%A9%AC%E7%A8%8B%E5%BA%8F%E5%91%98')
print(result2)
# 结果 a=黑马程序员
处理GET请求
GET请求一般用于向服务器获取数据 例如用百度搜索黑马程序员(URL是https://www.baidu.com/s?wd=%E9%BB%91%E9%A9%AC%E7%A8%8B%E5%BA%8F%E5%91%98)
import urllib.request
import urllib.parse
url="http://www.baidu.com/s"
word={"wd":"黑马程序员"}
word=urllib.parse.urlencode(word)
new_url=url+"?"+word
headers={"User-Agent":"Mozilla/5.0 (Window NT 10.0;WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36"}
requests=urllib.request.Request(new_url,headers=headers)
response=urllib.request.urlopen(requests)
html=response.read().decode('UTF-8')
print(html)
处理POST请求
以POST方式发送请求,urlopen()方法必须设置data参数。data参数以字典的形式存放数据
添加特定的Headers—请求伪装
将爬虫程序伪装成一个从浏览器发出的请求,需要自定义请求报头在发送request请求时,加入特定的Headers
只需要调用Request.get——header()
import urllib.request
url="http://www.itcast.cn"
user_agent={"User-Agent":"Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)"}
request=urllib.request.Request(url,headers=user_agent)
# 也可以通过调用Request.add.——headers() 添加/修改一个特定的header
request.add_header("Connection","keep-alive")
#也可以通过调用Request.get_header() 来查看header信息
request.get_header(header_name="Connection")
response=urllib.request.urlopen(request)
print(response.code)
html=response.read()
print(html)
代理服务器
-----网站限制IP访问的次数,—代理多用于防止“放爬虫”机制
简单的自定义opener
opener是urllib.request.OpenerDirector类的对象,之前使用的urlopen就是模块构建好的一个opener,但不支持代理 Cookie等其他的HTTP/HTTPS高级功能
1.使用相关的Handler处理器创建特定功能的处理器对象
2.通过urllib.request.build_opener()方法使用处理器对象创建自定义的opener对象
3.使用自定义的opener对象,调用open()方法发送请求
import urllib.request
# 构建一个HTTPHander处理器对象,支持处理HTTP请求
import requests
http_hanlder=urllib.request.HTTPHandler()
# 调用urllib2.build_opener()方法,创建支持处理HTTP请求的opener对象
opener=urllib.request.build_opener(http_hanlder)
request=urllib.request.Request("http://www.baidu.com/")
response=opener.open(request)
print(response.read())
设置代理服务器
可以使用urllib.request中的ProxyHandler()方法
import urllib.request
httpproxy_handler=urllib.request.ProxyHandler({"http":"172.16.221.70"})
nullproxy_handler=urllib.request.ProxyHandler({})
proxy_switch=True
if proxy_switch:
opener=urllib.request.build_opener(httpproxy_handler)
else:
opener=urllib.request.build_opener(nullproxy_handler)
request=urllib.request.Request("http://www.baidu.com/")
response=opener.open(request)
print(response.read())
常见的网络异常
当使用urlopen()方法发送HTTP请求时,如果urlopen不能处理返回的响应内容,就会产生错误
URLError异常和捕获
URLError产生的原因主要亚欧以下几种:
1.没有连接网络
2.服务器连接失败
3.找不到指定的服务器
可以使用try…except…语句捕获相应的异常
import urllib.request
import urllib.error
request=urllib.request.Request("http://www.ajkfhafwjqh.com")
try:
urllib.request.urlopen(request,timeout=5)
except urllib.error.URLError as err:
print(err)
# 结果:<urlopen error [Errno 11004] getaddrinfo failed>
HttpError异常和捕获
每个服务器的HTTP响应都会有一个数字响应码,有些表示无法处理请求内容,则会抛出异常
HttpError 是URLError的子类
requests库
requests 库
继承了urllib的所有特性,而且还支持一些其他的特性
1.requests.Requests:表示请求对象,将一个请求发送到服务器
2:requests.Response:表示响应对象,其中包含服务器对HTTP的响应
3.requests.Session:表示请求会话,支持Cookie持久性、连接池和配置
使用requests库GET请求爬取网页
import request
url="http://www.baidu.com/s"
param={"wd":"传智播客"}
headers={"User-Agent":"Mozilla/5.0 (Window NT 10.0;WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36"}
response=requests.get(url,params=param,headers=headers)
print(response.text)
发送请求
requests.request() :构造一个请求,支持以下方法的基础方法
requests.get() :获取HTML网页的主要方法,对应于HTTP的GET请求
requests.head() :获取HTML网页头信息的方法,对应HEAD请求方式
requests.post() :向HTML网页提交POST请求方法
.put() : PUT
.patch() :提交局部修改请求
.delete() : 删除请求
返回请求
ststus_code 200表示成功,404表示失败
text URL对应的页面内容
encoding 从请求头中猜测响应内容编码的方式
apparent_encoding 分析出响应编码的方式
content 响应内容的二进制形式