Request、Beautiful Soup、PyQuery的用法
Request的介绍
在入门教程中我们介绍了urllib库和urllib2的用法,同时我们了解一些爬虫的基础以及对爬虫有了基本的了解。其实在我们生产环境中,使用Request库更加方便与实用,同时我们这需要短短的几行代码就能解决大量的事情。
一、Request的安装
在Python简介与环境配置中我们已经安装了PIP管理工具,如果你是2.x版本,也可以使用easy_install来安装Request库,他可以帮助我们很容易的安装三方库:
1、使用pip安装Request
# pip2.x安装requests
pip install requests
# pip3.x安装requests
pip3 install requests
2、使用easy_install安装Request
easy_install requests
二、Request的使用
在python中引入三方模块非常简单,只需要import引入即可:
import requests
req = requests.get("https://ptorch.com")
print(req.text)
这样我们即可快速提取目标网页的代码,使用起来非常方便!
1、Request基本请求方式
你可以通过requests库发送所有的http请求:
requests.get("http://httpbin.org/get") #GET请求
requests.post("http://httpbin.org/post") #POST请求
requests.put("http://httpbin.org/put") #PUT请求
requests.delete("http://httpbin.org/delete") #DELETE请求
requests.head("http://httpbin.org/get") #HEAD请求
requests.options("http://httpbin.org/get") #OPTIONS请求
2、使用Request发送GET请求
想要使用爬虫获取某个目标网页,直接使用get方法即可发送HTTP GET请求:
req = requests.get("http://httpbin.org/get")
通常情况下我们不会只访问基础网页,特别是爬取动态网页时我们需要传递不同的参数获取不同的内容;GET传递参数有两种方法,可以直接在链接中添加参数或者利用params添加参数:
import requests
payload = {
'key1': 'value