目录
import requests
class RequestSpider(object):
def __init__(self):
url = 'https://www.baidu.com'
headers = {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.67 Safari/537.36'
}
self.response = requests.get(url, headers=headers)
def run(self):
data = self.response.content
# 获取请求头
request_headers = self.response.request.headers
# 获取响应头
coderesponse_headers = self.response.headers
# 响应状态码
code = self.response.status_code
# 请求的cookie
request_cookie = self.response.request._cookies
print(request_cookie)
# 响应的cookie
response_cookie = self.response.cookies
print(response_cookie)
RequestSpider().run()
一、GET请求
requests.get(url, params=None, **kwargs)
:param url: URL for the new :class:`Request` object.
:param params: (optional) Dictionary or bytes to be sent in the query string for the :class:`Request`.
:param \*\*kwargs: Optional arguments that ``request`` takes.
:return: :class:`Response <Response>` object
:rtype: requests.Response
1. 最基本的GET请求可以直接用get方法
import requests
response = requests.get("http://www.baidu.com/")
# 也可以这么写
response = requests.request("get", "http://www.baidu.com/")
# 内身份认证 auth
response = requests.get(url,auth=('username','password'))
print(response.status_code)
# content属性 返回的类型 是bytes
data = response.content.decode('utf-8')
# text 属性 返回的类型 是文本str
data = response.text
print(type(data))
2. 添加 headers 和 查询参数
如果想添加 headers,可以传入headers
参数来增加请求头中的headers信息。
如果要将参数放在url中传递