pip install requests |
import requests url = 'http://www.baidu.com/s' headers = { "User-Agent": "Mozilla/5.0 (WindowsNT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36" } params = { "wd": "测试-安静" } r = requests.get(url=url, params=params,headers=headers) print(r) print(r.url) if '测试-安静' in r.content.decode('utf-8'): print('请求成功!') |
r.status_code #响应状态码 r.content #字节方式的响应体,会自动为你解码 gzip 和 deflate 压缩 r.headers # 请求头信息 r.json() # Requests中SON r.url # 获取url r.encoding # 编码格式 r.cookies # 获取cookie r.text #字符串方式的响应体 |
import requests # 登录请求地址 url = 'http://apis.juhe.cn/simpleWeather/query' # 请求头 headers = { "User-Agent":"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36", } # body数据 data = { 'city': "上海", # 账号 "key": "331eab8f3481f37868378fcdc76cb7cd", # 密码 } # 发送请求 r = requests.post(url, headers=headers, data=data) print(r.text) |
import requests url ="http://httpbin.org/post" # 添加json数据 json = { "username":"AnJing", "password":"123456" } # 通过json方式添加数据 r =requests.post(url,json=json) print(r.text) |
import requests url ="https://www.51testing.org/htm/brandpc/PZ.html" r = requests.get(url, verify=False) print(r.text) |
# coding:utf-8 import requests import urllib3 urllib3.disable_warnings() s = requests.session() s.verify = False url = 'https://passport.cnblogs.com/user/signin' headers = { "User-Agent":"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.81 Safari/537.36" } r = s.get(url,headers=headers) cooks = { ".Cnblogs.AspNetCore.Cookies":"这里写入抓取到的cookies值", ".CNBlogsCookie":"抓取到的cookies值" } c = requests.cookies.RequestsCookieJar() # 登陆有效的cookies c.set(".CNBlogsCookie", cooks[".CNBlogsCookie"]) c.set(".Cnblogs.AspNetCore.Cookies", cooks[".Cnblogs.AspNetCore.Cookies"]) # 将cookies值全部添加到session中 s.cookies.update(c) # 访问后台地址,确定是否登录成功 url1 = "https://i.cnblogs.com/posts/edit" r1 = s.get(url1) result = r1.content.decode('utf-8') if "博客后台 - 博客园" in result: print("登录成功!") |
# coding:utf-8 import requests url = 'http://github.com' # 重定向为False r = requests.get(url, allow_redirects=False) print('拒绝重定向请求的状态码:%s'%(r.status_code)) print('拒绝重定向请求地址:%s'%(r.url)) # 重定向为True(默认为True) r2 = requests.get(url) print('允许重定向请求的状态码:%s'%(r2.status_code)) print('允许重定向请求地址:%s'%(r2.url)) |
欢迎光临 51Testing软件测试论坛 (http://bbs.51testing.com/) | Powered by Discuz! X3.2 |