【原创】初探python请求库(requests&urllib)

admin 2022年12月3日16:31:40评论45 views字数 2014阅读6分42秒阅读模式

[huayang]

resquests

import requests

发送无参数的get请求

response = requests.get('http://www.baidu.com')

# 发送无参数的get请求 设置超时时间 timeout 单位秒

response = requests.get('http://www.baidu.com', timeout=1)

查看当前返回状态码

print(response.status_code)

查看当前返回内容 text返回的是字符串

print(response.text)

查看当前返回内容 content返回的是字节流

print(response.content)

若要返回的内容为json

print(response.json())

查看请求头信息(headers)

print(response.headers)

查看请求头中某一个参数的信息

print(response.headers['Set-Cookie'])

自定义headers发送

import requests
headers = {
    'User-Agent' : 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.85 Safari/537.36',
    'Host':'hellohy.top'
}
response = requests.get('https://hellohy.top',headers=headers)
print(response.text)

查看Cookiea

print(response.cookies)

自定义Cookies发送

    headers = {
        'User-Agent': 'Mozilla/5.0',
        'Cookie': '123'
    }

设置代理

proxies = {

"http": "http://10.10.1.10:3128",

"https": "http://10.10.1.10:1080"

}
requests.get("http://baidu.com", proxies=proxies)

通过requests获取session

session = requests.Session()

# 举例:登录名 密码  key为登陆表单中对应的input的name值

login_data = {'email': '[email protected]', 'password': 'password'}

# 发送数据

session.post("http://pythontab.com/testLogin", login_data)

# 获取发送的session

session_response = session.get('http://pythontab.com/notification/')

print('session请求返回的状态码为:' + str(session_response.status_code))

post请求

import requests

data = {
    'naem' : 'adnmin',
    'password' : '123456'
}

response = requests.post('https://hellohy.top',data=data)

print(response.text)

urllib

urlopen()方法可以实现最基本的请求的发起,但如果要加入Headers等信息,就可以利用Request类来构造请求

【原创】初探python请求库(requests&urllib)
urllib.request.Request(url, data=None, headers={}, origin_req_host=None, unverifiable=False, method=None)
import urllib.request

get请求

res = urllib.request.urlopen('http://18.140.63.226/public/plugins/alertlist/../../../../../../../../etc/passwd', timeout=3)

post请求

headers = {'Accept-Charset': 'utf-8', 'Content-Type': 'application/json'}

req = urllib.request.Request(url=path,  headers=headers, method='POST')
response = urllib.request.urlopen(req).read()

code值

re = urllib.request.Request(url=paylaod, headers=headers)
res = urllib.request.urlopen(re, timeout=3)
code = res.getcode()

[/huayang]

FROM:浅浅淡淡[hellohy]

  • 左青龙
  • 微信扫一扫
  • weinxin
  • 右白虎
  • 微信扫一扫
  • weinxin
admin
  • 本文由 发表于 2022年12月3日16:31:40
  • 转载请保留本文链接(CN-SEC中文网:感谢原作者辛苦付出):
                   【原创】初探python请求库(requests&urllib)https://cn-sec.com/archives/1442867.html

发表评论

匿名网友 填写信息