python教程:requests库使用方法详解

python的requests的使用 本文详细讲解了requests库的API和使用案例,并加上了代码注释,希望能对大家学习requests库有所帮助。 阅读详情

1.官方文档

requests的具体安装过程请看:http://docs.python-requests.org/en/latest/user/install.html#install
requests的官方指南文档:http://docs.python-requests.org/en/latest/user/quickstart.html
requests的高级指南文档:http://docs.python-requests.org/en/latest/user/advanced.html#advanced

2.什么是Requests

Requests 是⽤imgython语⾔编写,基于urllib,采⽤Apache2 Licensed开源协议的 HTTP 库。它⽐ urllib 更加⽅便,
可以节约我们⼤量的⼯作,完全满⾜HTTP测试需求。

⼀句话——Python实现的简单易⽤的HTTP库

安装Requests库

进入命令行win+R执行

  • 命令:pip install requests

  • 项目导入:import requests

各种请求方式

直接上代码,不明白可以查看我的urllib的基本使用方法

import requests

requests.post('http://httpbin.org/post')
requests.put('http://httpbin.org/put')
requests.delete('http://httpbin.org/delete')
requests.head('http://httpbin.org/get')
requests.options('http://httpbin.org/get')

这么多请求方式,都有什么含义,所以问下度娘:

  • GET: 请求指定的页面信息,并返回实体主体。
  • HEAD: 只请求页面的首部。
  • POST: 请求服务器接受所指定的文档作为对所标识的URI的新的从属实体。
  • PUT: 从客户端向服务器传送的数据取代指定的文档的内容。
  • DELETE: 请求服务器删除指定的页面。
  • get 和 post比较常见 GET请求将提交的数据放置在HTTP请求协议头中
  • POST提交的数据则放在实体数据中
基本的GET请求
import requests

response = requests.get('http://httpbin.org/get')
print(response.text)
返回值:

{
    "args": {}, 
    "headers": {
    "Accept": "*/*", 
    "Accept-Encoding": "gzip, deflate", 
    "Connection": "close", 
    "Host": "httpbin.org", 
    "User-Agent": "python-requests/2.18.4"
  }, 
  "origin": "183.64.61.29", 
  "url": "http://httpbin.org/get"
}


(4)、获取二进制数据

记住返回值.content就ok了

import requests

response = requests.get("https://github.com/favicon.ico")
print(type(response.text), type(response.content))
print(response.text)
print(response.content)
带参数的GET请求

将name和age传进去

import requests

response = requests.get("http://httpbin.org/get?name=germey&age=22")
print(response.text)
{
    "args": {
    "age": "22", 
    "name": "germey"
  }, 
    "headers": {
    "Accept": "*/*", 
    "Accept-Encoding": "gzip, deflate", 
    "Connection": "close", 
    "Host": "httpbin.org", 
    "User-Agent": "python-requests/2.18.4"
  }, 
  "origin": "183.64.61.29", 
  "url": "http://httpbin.org/get?name=germey&age=22"
}
或者使用params的方法:

import requests

data = {
 'name': 'germey',
 'age': 22
}
response = requests.get("http://httpbin.org/get", params=data)
print(response.text)

返回值一样

返回值为二进制不必再进行展示,

解析json

将返回值已json的形式展示:

import requests

import json


response = requests.get("http://httpbin.org/get")

print(type(response.text))

print(response.json())

print(json.loads(response.text))

print(type(response.json()))

返回值:


<class 'str'>

{'args': {}, 'headers': {'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate', 'Connection': 'close', 'Host': 'httpbin.org', 'User-Agent': 'python-requests/2.18.4'}, 'origin': '183.64.61.29', 'url': 'http://httpbin.org/get'}

{'args': {}, 'headers': {'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate', 'Connection': 'close', 'Host': 'httpbin.org', 'User-Agent': 'python-requests/2.18.4'}, 'origin': '183.64.61.29', 'url': 'http://httpbin.org/get'}

<class 'dict'>
添加headers

有些网站访问时必须带有浏览器等信息,如果不传入headers就会报错,如下

import requests

response = requests.get("https://www.zhihu.com/explore")
print(response.text)
返回值:

<html><body><h1>500 Server Error</h1>
An internal server error occured.
</body></html>
当传入headers时:

import requests

headers = {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36'
}
response = requests.get("https://www.zhihu.com/explore", headers=headers)
print(response.text)

成功返回网页源代码不做展示

基本POST请求

不明白见urllib的使用方法

import requests

data = {'name': 'germey', 'age': '22'}
response = requests.post("http://httpbin.org/post", data=data)
print(response.text)

返回:

{
   "args": {}, 
   "data": "", 
   "files": {}, 
   "form": {
    "age": "22", 
    "name": "germey"
   }, 
    "headers": {
    "Accept": "*/*", 
    "Accept-Encoding": "gzip, deflate", 
    "Connection": "close", 
    "Content-Length": "18", 
    "Content-Type": "application/x-www-form-urlencoded", 
    "Host": "httpbin.org", 
    "User-Agent": "python-requests/2.18.4"
  }, 
  "json": null, 
  "origin": "183.64.61.29", 
  "url": "http://httpbin.org/post"
}

3.响应

response属性
import requests
response = requests.get('http://www.jianshu.com')
print(type(response.status_code), response.status_code)
print(type(response.headers), response.headers)
print(type(response.cookies), response.cookies)
print(type(response.url), response.url)
print(type(response.history), response.history)
return:
<class 'int'> 200
<class 'requests.structures.CaseInsensitiveDict'> {'Date': 'Thu, 01 Feb 2018 20:47:08 GMT', 'Server': 'Tengine', 'Content-Type': 'text/html; charset=utf-8', 'Transfer-Encoding': 'chunked', 'X-Frame-Options': 'DENY', 'X-XSS-Protection': '1; mode=block', 'X-Content-Type-Options': 'nosniff', 'ETag': 'W/"9f70e869e7cce214b6e9d90f4ceaa53d"', 'Cache-Control': 'max-age=0, private, must-revalidate', 'Set-Cookie': 'locale=zh-CN; path=/', 'X-Request-Id': '366f4cba-8414-4841-bfe2-792aeb8cf302', 'X-Runtime': '0.008350', 'Content-Encoding': 'gzip', 'X-Via': '1.1 gjf22:8 (Cdn Cache Server V2.0), 1.1 PSzqstdx2ps251:10 (Cdn Cache Server V2.0)', 'Connection': 'keep-alive'}
<class 'requests.cookies.RequestsCookieJar'> <RequestsCookieJar[<Cookie locale=zh-CN for www.jianshu.com/>]>
<class 'str'> https://www.jianshu.com/
<class 'list'> [<Response [301]>]

状态码判断:常见的网页状态码:

100: ('continue',),
101: ('switching_protocols',),
102: ('processing',),
103: ('checkpoint',),
122: ('uri_too_long', 'request_uri_too_long'),
    
200: ('ok', 'okay', 'all_ok', 'all_okay', 'all_good', '\\o/', '✓'),
201: ('created',),
202: ('accepted',),
203: ('non_authoritative_info', 'non_authoritative_information'),
204: ('no_content',),
205: ('reset_content', 'reset'),
206: ('partial_content', 'partial'),
207: ('multi_status', 'multiple_status', 'multi_stati', 'multiple_stati'),
208: ('already_reported',),
226: ('im_used',),
    
# Redirection.
300: ('multiple_choices',),
301: ('moved_permanently', 'moved', '\\o-'),
302: ('found',),
303: ('see_other', 'other'),
304: ('not_modified',),
305: ('use_proxy',),
306: ('switch_proxy',),
307: ('temporary_redirect', 'temporary_moved', 'temporary'),
308: ('permanent_redirect','resume_incomplete', 'resume',), # These 2 to be removed in 3.0
    
# Client Error.
400: ('bad_request', 'bad'),
401: ('unauthorized',),
402: ('payment_required', 'payment'),
403: ('forbidden',),
404: ('not_found', '-o-'),
405: ('method_not_allowed', 'not_allowed'),
406: ('not_acceptable',),
407: ('proxy_authentication_required', 'proxy_auth', 'proxy_authentication'),
408: ('request_timeout', 'timeout'),
409: ('conflict',),
410: ('gone',),
411: ('length_required',),
412: ('precondition_failed', 'precondition'),
413: ('request_entity_too_large',),
414: ('request_uri_too_large',),
415: ('unsupported_media_type', 'unsupported_media', 'media_type'),
416: ('requested_range_not_satisfiable', 'requested_range', 'range_not_satisfiable'),
417: ('expectation_failed',),
418: ('im_a_teapot', 'teapot', 'i_am_a_teapot'),
421: ('misdirected_request',),
422: ('unprocessable_entity', 'unprocessable'),
423: ('locked',),
424: ('failed_dependency', 'dependency'),
425: ('unordered_collection', 'unordered'),
426: ('upgrade_required', 'upgrade'),
428: ('precondition_required', 'precondition'),
429: ('too_many_requests', 'too_many'),
431: ('header_fields_too_large', 'fields_too_large'),
444: ('no_response', 'none'),
449: ('retry_with', 'retry'),
450: ('blocked_by_windows_parental_controls', 'parental_controls'),
451: ('unavailable_for_legal_reasons', 'legal_reasons'),
499: ('client_closed_request',),
    
# Server Error.
500: ('internal_server_error', 'server_error', '/o\\', '✗'),
501: ('not_implemented',),
502: ('bad_gateway',),
503: ('service_unavailable', 'unavailable'),
504: ('gateway_timeout',),
505: ('http_version_not_supported', 'http_version'),
506: ('variant_also_negotiates',),
507: ('insufficient_storage',),
509: ('bandwidth_limit_exceeded', 'bandwidth'),
510: ('not_extended',),
511: ('network_authentication_required', 'network_auth', 'network_authentication'),

4.高级操作

文件上传

使用 Requests 模块,上传文件也是如此简单的,文件的类型会自动进行处理:

实例:

import requests

files = {'file': open('cookie.txt', 'rb')}
response = requests.post("http://httpbin.org/post", files=files)
print(response.text)

这是通过测试网站做的一个测试,返回值如下:

{
"args": {}, 
"data": "", 
"files": {
"file": "#LWP-Cookies-2.0\r\nSet-Cookie3: BAIDUID=\"D2B4E137DE67E271D87F03A8A15DC459:FG=1\"; path=\"/\"; domain=\".baidu.com\"; path_spec; domain_dot; expires=\"2086-02-13 11:15:12Z\"; version=0\r\nSet-Cookie3: BIDUPSID=D2B4E137DE67E271D87F03A8A15DC459; path=\"/\"; domain=\".baidu.com\"; path_spec; domain_dot; expires=\"2086-02-13 11:15:12Z\"; version=0\r\nSet-Cookie3: H_PS_PSSID=25641_1465_21087_17001_22159; path=\"/\"; domain=\".baidu.com\"; path_spec; domain_dot; discard; version=0\r\nSet-Cookie3: PSTM=1516953672; path=\"/\"; domain=\".baidu.com\"; path_spec; domain_dot; expires=\"2086-02-13 11:15:12Z\"; version=0\r\nSet-Cookie3: BDSVRTM=0; path=\"/\"; domain=\"www.baidu.com\"; path_spec; discard; version=0\r\nSet-Cookie3: BD_HOME=0; path=\"/\"; domain=\"www.baidu.com\"; path_spec; discard; version=0\r\n"
}, 
"form": {}, 
"headers": {
"Accept": "*/*", 
"Accept-Encoding": "gzip, deflate", 
"Connection": "close", 
"Content-Length": "909", 
"Content-Type": "multipart/form-data; boundary=84835f570cfa44da8f4a062b097cad49", 
"Host": "httpbin.org", 
"User-Agent": "python-requests/2.18.4"
}, 
"json": null, 
"origin": "183.64.61.29", 
"url": "http://httpbin.org/post"
}
获取cookie

当需要cookie时,直接调用response.cookieimgresponse为请求后的返回值)

import requests

response = requests.get("https://www.baidu.com")
print(response.cookies)
for key, value in response.cookies.items():
print(key + '=' + value)

输出结果:

<RequestsCookieJar[<Cookie BDORZ=27315 for .baidu.com/>]>
BDORZ=27315

会话维持、模拟登陆

如果某个响应中包含一些Cookie,你可以快速访问它们:

import requests

r = requests.get('http://www.google.com.hk/')
print(r.cookies['NID'])
print(tuple(r.cookies))

要想发送你的cookies到服务器,可以使用 cookies 参数:

import requests

url = 'http://httpbin.org/cookies'
cookies = {'testCookies_1': 'Hello_Python3', 'testCookies_2': 'Hello_Requests'}

# 在Cookie Version 0中规定空格、方括号、圆括号、等于号、逗号、双引号、斜杠、问号、@,冒号,分号等

特殊符号都不能作为Cookie的内容。

r = requests.get(url, cookies=cookies)
print(r.json())
证书验证(SSL Cert Verification)
#证书验证(大部分网站都是https)
import requests
respone=requests.get('https://www.12306.cn') #如果是ssl请求,首先检查证书是否合法,不合法则报错,程序终端


#改进1:去掉报错,但是会报警告
import requests
respone=requests.get('https://www.12306.cn',verify=False) #不验证证书,报警告,返回200
print(respone.status_code)


#改进2:去掉报错,并且去掉警报信息
import requests
from requests.packages import urllib3
urllib3.disable_warnings() #关闭警告
respone=requests.get('https://www.12306.cn',verify=False)
print(respone.status_code)

#改进3:加上证书
#很多网站都是https,但是不用证书也可以访问,大多数情况都是可以携带也可以不携带证书
#知乎\百度等都是可带可不带
#有硬性要求的,则必须带,比如对于定向的用户,拿到证书后才有权限访问某个特定网站
import requests
respone=requests.get('https://www.12306.cn',
                     cert=('/path/server.crt',
                           '/path/key'))
print(respone.status_code)
认证设置
#官网链接:http://docs.python-requests.org/en/master/user/authentication/

#认证设置:登陆网站是,弹出一个框,要求你输入用户名密码(与alter很类似),此时是无法获取html的
# 但本质原理是拼接成请求头发送
#         r.headers['Authorization'] = _basic_auth_str(self.username, self.password)
# 一般的网站都不用默认的加密方式,都是自己写
# 那么我们就需要按照网站的加密方式,自己写一个类似于_basic_auth_str的方法
# 得到加密字符串后添加到请求头
#         r.headers['Authorization'] =func('.....')

#看一看默认的加密方式吧,通常网站都不会用默认的加密设置
import requests
from requests.auth import HTTPBasicAuth
r=requests.get('xxx',auth=HTTPBasicAuth('user','password'))
print(r.status_code)

#HTTPBasicAuth可以简写为如下格式
import requests
r=requests.get('xxx',auth=('user','password'))
print(r.status_code)
代理设置

在进行爬虫爬取时,有时候爬虫会被服务器给屏蔽掉,这时采用的方法主要有降低访问时间,通过代理ip访问,
如下:

import requests

proxies = {
"http": "http://127.0.0.1:9743",
"https": "https://127.0.0.1:9743",
}


response = requests.get("https://www.taobao.com", proxies=proxies)
print(response.status_code)

ip可以从网上抓取,或者某宝购买

如果代理需要设置账户名和密码,只需要将字典更改为如下:

proxies = {
"http":"http://user:password@127.0.0.1:9999"
}

如果你的代理是通过sokces这种方式则需要

pip install "requests[socks]"
proxies= {
"http":"socks5://127.0.0.1:9999",
"https":"sockes5://127.0.0.1:8888"
}

超时设置

访问有些网站时可能会超时,这时设置好timeout就可以解决这个问题

import requests
from requests.exceptions import ReadTimeout
try:
response = requests.get("http://httpbin.org/get", timeout = 0.5)
print(response.status_code)
except ReadTimeout:
print('Timeout')

正常访问,状态吗返回200

认证设置

如果碰到需要认证的网站可以通过requests.auth模块实现

import requests

from requests.auth import HTTPBasicAuth

response = requests.get("http://120.27.34.24:9001/",auth=HTTPBasicAuth("user","123"))
print(response.status_code)

当然这里还有一种方式

import requests

response = requests.get("http://120.27.34.24:9001/",auth=("user","123"))
print(response.status_code)
异常处理

遇到网络问题(如:DNS查询失败、拒绝连接等)时,Requests会抛出一个ConnectionError 异常。

遇到罕见的无效HTTP响应时,Requests则会抛出一个 HTTPError 异常。

若请求超时,则抛出一个 Timeout 异常。

若请求超过了设定的最大重定向次数,则会抛出一个 TooManyRedirects 异常。

所有Requests显式抛出的异常都继承自 requests.exceptions.RequestException 。

上传文件
import requests
files={'file':open('a.jpg','rb')}
respone=requests.post('http://httpbin.org/post',files=files)
print(respone.status_code)
带参数的GET请求->headers

通常我们在发送请求时都需要带上请求头,请求头是将自身伪装成浏览器的关键,常见的有用的请求头如下

Host

Referer #大型网站通常都会根据该参数判断请求的来源
User-Agent #客户端
Cookie #Cookie信息虽然包含在请求头里,但requests模块有单独的参数来处理他,headers={}内就不要放它了

添加headers(浏览器会识别请求头,不加可能会被拒绝访问,比如访问https://www.zhihu.com/explore)

import requests
response=requests.get('https://www.zhihu.com/explore')
response.status_code #500

#学习中遇到问题没人解答?小编创建了一个Python学习交流群:711312441
#自己定制headers
headers={
    'User-Agent':'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.76 Mobile Safari/537.36',

}
respone=requests.get('https://www.zhihu.com/explore',
                     headers=headers)
print(respone.status_code) #200
带参数的GET请求->cookies
import requests

Cookies={   'user_session':'rzNme4L6LTH7QSresq8w0BVYhTNt5GS-asNnkOe7_FZ2CjB6',
}

response=requests.get('https://github.com/settings/emails',
             cookies=Cookies) #github对请求头没有什么限制,我们无需定制user-agent,对于其他网站可能还需要定制


print('********@**.com' in response.text) #True
发送post请求,模拟浏览器的登录行为

对于登录来说,应该输错用户名或密码然后分析抓包流程,用脑子想一想,输对了浏览器就跳转了,还分析个毛线,累死你也找不到包

自动登录gitbub(自己处理cookies))

'''
一 目标站点分析
    浏览器输入https://github.com/login
    然后输入错误的账号密码,抓包
    发现登录行为是post提交到:https://github.com/session
    而且请求头包含cookie
    而且请求体包含:
        commit:Sign in
        utf8:✓
        authenticity_token:lbI8IJCwGslZS8qJPnof5e7ZkCoSoMn6jmDTsL1r/m06NLyIbw7vCrpwrFAPzHMep3Tmf/TSJVoXWrvDZaVwxQ==
        login:egonlin
        password:123


二 流程分析
    先GET:https://github.com/login拿到初始cookie与authenticity_token
    返回POST:https://github.com/session, 带上初始cookie,带上请求体(authenticity_token,用户名,密码等)
    最后拿到登录cookie

    ps:如果密码时密文形式,则可以先输错账号,输对密码,然后到浏览器中拿到加密后的密码,github的密码是明文
'''

import requests
import re

#第一次请求
r1=requests.get('https://github.com/login')
r1_cookie=r1.cookies.get_dict() #拿到初始cookie(未被授权)
authenticity_token=re.findall(r'name="authenticity_token".*?value="(.*?)"',r1.text)[0] #从页面中拿到CSRF TOKEN

#第二次请求:带着初始cookie和TOKEN发送POST请求给登录页面,带上账号密码
data={
    'commit':'Sign in',
    'utf8':'✓',
    'authenticity_token':authenticity_token,
    'login':'********@**.com',
    'password':'alex3714'
}
r2=requests.post('https://github.com/session',
             data=data,
             cookies=r1_cookie
             )


login_cookie=r2.cookies.get_dict()


#第三次请求:以后的登录,拿着login_cookie就可以,比如访问一些个人配置
r3=requests.get('https://github.com/settings/emails',
                cookies=login_cookie)

print('********@**.com' in r3.text) #True

requests.session()自动帮我们保存cookie信息

import requests
import re

session=requests.session()
#第一次请求
r1=session.get('https://github.com/login')
authenticity_token=re.findall(r'name="authenticity_token".*?value="(.*?)"',r1.text)[0] #从页面中拿到CSRF TOKEN

#第二次请求
data={
    'commit':'Sign in',
    'utf8':'✓',
    'authenticity_token':authenticity_token,
    'login':'********@**.com',
    'password':'alex3714'
}
r2=session.post('https://github.com/session',
             data=data,
             )

#第三次请求
r3=session.get('https://github.com/settings/emails')

print('********@**.com' in r3.text) #True

补充json

json的用法

requests.post(url='xxxxxxxx',
              data={'xxx':'yyy'}) #没有指定请求头,#默认的请求头:application/x-www-form-urlencoed

#如果我们自定义请求头是application/json,并且用data传值, 则服务端取不到值
requests.post(url='',
              data={'':1,},
              headers={
                  'content-type':'application/json'
              })


requests.post(url='',
              json={'':1,},
              ) #默认的请求头:application/json
Python中requests库 文章目录requests库一、 基本概念1、 简介2、 获取3、 http 协议3.1 URL3.2 常用 http 请求方法二、 使用方法1、 基本语法requests 库中的方法2、 具体使用方法2.1 get2.1.1 基本语法2.1.2 常用参数2.2 post2.2.1 基本语法2.2.2 常用参数2.3 response2.4 **head**2.4.1 基本语法2.5 put requests库 一、 基本概念 1、 简介 requests 模块是 python 基于 urllib,采用 A 阅读详情

相关推荐

史上最全,Python爬虫requests库。你必须得会。

Requests 是一个为人类设计的简单而优雅的 HTTP 库。requests 库是一个原生的 HTTP 库,比 urllib3 库更为容易使用。requests 库发送原生的 HTTP 1.1 请求,无需手动为 URL 添加查询串, 也不需要对 POST 数据进行表单编码。相对于 urllib3 库, requests 库拥有完全自动化 Keep-alive 和 HTTP 连接池的功能。requests 库包含的特性如下。❖ 1Keep-Alive & 连接池❖ 国际化域名和 URL。

爬遍所有网站 1872

python—requests模块详解

requests模块详解

W0ngk,一个安全菜鸡,一直在模仿,尚未有超越。 1万+

网络爬虫基础教程:使用 Python 的 requests 库进行网页数据抓取

网络爬虫是一种自动化程序,用于从互联网上抓取数据。无论是用于数据分析、市场研究、学术研究,还是搜索引擎的网页索引,爬虫技术都在现代互联网应用中发挥着重要作用。本文将通过 requests来讲解如何进行基本的网页数据抓取。requests是 Python 中一个简单易用的库,它通过封装 HTTP 请求,简化了网络请求的过程,是实现网络爬虫的理想选择。

这里只有干货:从 Modbus 通信到 MES 对接,从 YOLO 训练到工控机部署,带你搞定工业软件开发全流程。 1028

python导入requests库_浅谈python中requests模块导入的问题

今天使用Pycharm来抓取网页图片时候,要导入requests模块,但是在pycharm中import requests 时候报错。原因: python中还没有安装requests库解决办法:1.先找到自己python安装目录下的pip2.在自己的电脑里打开cmd窗口。先点击开始栏,在搜索栏输入cmd,按Enter,打打开cmd窗口。在cmd里将目录切换到你的pip所在路径。比如我的在C:\Py...

weixin_39605347的博客 1478

【Python爬虫教程】基础篇-08 requests库详解

摘要:python requests库基用法,高级用法

仲君Johnny的博客 1583

从稳压管到LDO芯片:一张图看懂线性电源的‘内卷’进化史

本文追溯了从稳压管到LDO芯片的线性电源技术进化历程,详细解析了各阶段的技术突破与局限。重点探讨了现代LDO在超低功耗、高精度控制等方面的创新,并提供了实战选型的黄金法则,帮助工程师在电子设备小型化与低功耗化趋势中做出最优选择。

weixin_42525551的博客 206

Python requests模块(request和response)

Python requests模块(request和response)

晴天的博客 6074

别再只会插卡了!用示波器实测SIM卡上电时序与通信波形(附故障排查)

本文深入解析了SIM卡通信的电气信号与时序规则,通过示波器实测波形揭示SIM卡上电时序与通信协议的关键细节。从VCC、CLK、RST、DATA四路信号的协同工作,到ATR(Answer to Reset)的解析,再到常见故障的波形诊断与排查方法,为硬件工程师提供了实用的调试指南。文章还分享了高级调试技巧与现代化工具链搭建建议,帮助提升物联网设备SIM卡通信的可靠性与效率。

weixin_42567279的博客 327

python的requests库全部教程_python requests 库教程

入门发送请求:r = requests.get("http://httpbin.org/get") # GETr = requests.post("http://httpbin.org/post") # POSTr = requests.put("http://httpbin.org/put") # PUTr = requests.delete("http:/...

weixin_39584549的博客 235

C++ 核电站

问题描述 一个核电站有n个放核物质的坑,排列在一条直线上。如果连续m个坑中放入核物质就会发生爆炸,所以某些坑中不能放核物质。 本题的任务:对于给定的n和m,求不发生爆炸的放置核物质的方案总数。 输入格式 第一行两个正整数n和m,之间用一个空格隔开。2≤n≤50,2≤m≤5。 输出格式 一行一个正整数,表示方案总数。 输入样例 4 3 输出样例 13 数据规模与约定 2≤n≤50,2≤m≤5 CODE #include<bits/stdc++.h> using namespace

HybridCOW_HORSE的博客 1803

从零到一:STM32G431的DSP库集成与FFT实战避坑指南

本文详细介绍了在STM32G431微控制器上集成CMSIS-DSP库并进行FFT实战开发的完整流程。重点解析了通过CubeMX和Keil环境配置DSP库的关键步骤、编译器宏定义陷阱及解决方案,并提供了FFT算法优化、内存管理及常见问题诊断的实用技巧,帮助开发者高效实现嵌入式信号处理应用。

oauth7security的博客 768

python的requests库全部教程_python3 爬虫学习python爬虫库-requests使用方法详细介绍...

python3 爬虫库requests介绍在python3的爬虫库中,requests是日常使用的非常多的第三方库之一。# requests库安装命令pip install requests# 如果安装超时,可以更换国内源安装,以下为清华源pip install -i https://pypi.tuna.tsinghua.edu.cn/simple requestsrequests使用示例#导入r...

weixin_39633252的博客 217

ABAP RAP 行为建模深入学习:从 Behavior Definition 到 Behavior Implementation 的完整实践指南

ABAP RAP开发指南:业务行为定义与实现 本文介绍SAP RAP框架中业务对象行为的开发方法: 分层设计 Behavior Definition声明业务能力(增删改查、校验、动作等) Behavior Implementation在ABAP类中编写具体逻辑 核心组件 使用BDL定义业务行为 通过FOR BEHAVIOR OF绑定行为池类(ABP) 在本地类实现校验/确定/动作逻辑 关键特性 支持managed/unmanaged两种实现模式 提供草稿表、并发控制等企业级功能 通过EML以别名访问实体 开

2007 年 ~ 2025 年,深耕 SAP 技术 18 年 413

Python Requests库简明使用教程

Requests是一常用的http请求库,它使用python语言编写,可以方便地发送http请求,以及方便地处理响应结果。一、安装1.1 使用PIP进行安装要安装requests,最方便快捷发方法的使用pip进行安装。 pip install requests 如果还没有安装pip,这个链接 Properly Installing Python 详细介绍了在各种平台下如何安装python以及s

Leo的博客 6万+

【Qwen2微调实战】LLaMA-Factory框架对Qwen2-7B模型的微调实践

在人工智能的浪潮中,大型语言模型(LLMs)正逐渐成为研究和应用的热点。它们在自然语言处理(NLP)的各个领域,如文本生成、翻译、问答等任务中展现出了卓越的能力。Qwen2-7B模型,作为该领域的佼佼者,不仅因其庞大的参数量和强大的表示能力受到关注,更因其在微调后能够更好地适应特定任务而备受关注。本文将详细介绍如何利用LLaMA-Factory这一高效的微调框架对Qwen2-7B进行微调,以期达到提升模型在特定任务上的表现。

寻道AI,探索AI无限可能! 2万+

Python爬虫实战:基于最新技术栈的政府招标采购数据抓取与分析

对于企业、研究人员和数据分析师来说,能够高效地获取这些数据意味着可以获得宝贵的商业洞察和市场先机。随着反爬技术的不断升级和网站结构的日益复杂,传统的爬虫方法已经难以满足需求。我们将采用Selenium、Playwright等现代浏览器自动化工具,结合Scrapy框架和异步请求库,构建一个能够应对各种反爬措施的强大爬虫系统。Playwright是微软开发的浏览器自动化工具,支持Chromium、WebKit和Firefox,比Selenium更快速、更稳定。

2201_76125261的博客 1312

【python】Python爬虫入门教程:使用requests库

本文介绍了使用Python的requests库编写爬虫的基本方法,以豆瓣电影Top250为例。主要内容包括:1) 安装requests和BeautifulSoup库;2) 爬虫项目结构规划;3) 完整代码实现,包含请求处理、HTML解析、数据存储和爬虫控制;4) 代码解析和优化建议。该爬虫可爬取电影标题、评分、简介等信息并保存为CSV文件,同时通过随机延时避免被封IP。文章还给出了异常处理、代理IP、异步请求等进阶优化方向。

weixin_56334307的博客 7057

从养殖场到科技前沿:YOLOv11+OpenCV精准计数鸡蛋与鸡

YOLOv11结合OpenCV技术,精准识别和计数鸡蛋与鸡,广泛应用于养殖场、市场监控和自动化包装。通过深度学习与计算机视觉,提升农业生产效率,让智能化管理更简单高效。

专注于深入研究多种编程语言,以实战为导向,逐步拓展开发技能,提升工程化编码和思维能力,展现无敌技术实力。 1206

【python教程】requests库的基本用法

文章目录😀前言📕往期知识点😀request库的安装(1) 直接安装的方法(2) pycharm安装的方法😀request基本用法(1) 请求方法(1) 发送请求(2) 传递url参数(3) 响应(4) 定制请求头 😀前言 requests是一个很实用的Python HTTP客户端库,爬虫和测试服务器响应数据时经常会用到,requests是Python语言的第三方的库,专门用于发送HTTP请求,使用起来比urllib简洁很多。 📕往期知识点 📕往期内容回顾 💡 python教程】保姆版教使用pymysq

flyskymood的博客 1万+

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

Data-Structures-and-Algorithm-Analysis-in-Java.pdf

作者: Weiss, Mark A. 出版社: Addison Wesley Data Structures and Algorithm Analysis in Java is an “advanced algorithms” book that fits between traditional CS2 and Algorithms Analysis courses. In the old ACM Curriculum Guidelines, this course was known as CS7. This text is for readers who want to learn good programming and algorithm analysis skills simultaneously so that they can develop such programs with the maximum amo...

python下载requests库教程_Python爬虫之requests库入门

网络爬虫就是提取网页的信息。网络爬虫的原则就是谨记“the website is API”,就是我们所面对的对象和信息来源都是各个website。现在python由于其特性已经越来越被广泛的用于网络爬虫领域。我们先从最简单的python爬虫库requests库开始讲起。首先我们从官网下载并安装好requests库。Paste_Image.pngrequests库的get方法Paste_Image....

weixin_39628864的博客 2050

锂电池充电器电路设计 里面有电路

锂电池充电器电路设计 里面有电路 3.7V升压到5V电路设计。

python的requests库全部教程_Python爬虫小白入门(二)requests库

一、前言为什么要先说Requests库呢,因为这是个功能很强大的网络请求库,可以实现跟浏览器一样发送各种HTTP请求来获取网站的数据。网络上的模块、库、包指的都是同一种东西,所以后文中可能会在不同地方使用不同称谓,不要迷惑哦。结合一个实例来讲解吧。我的一个设计师小伙伴常去一些设计类网站收集素材,其中有个网站Unsplash里面美图特别多,所以想要把里面的图片都保存下来,这样咱们的小爬虫就登场了。说...

weixin_39756696的博客 150

计算机控制技术及应用

《计算机控制技术及应用》通过总结作者的科研成果和吸收国内外的先进理论、方法和技术,以计算机控制系统的网络化、开放化、智能化和集成化发展趋势为主线索,主要介绍计算机控制系统的基本概念和计算机控制系统的典型形式,计算机控制系统的数学描述与基本分析方法,以及数字PID控制器、最少拍控制系统、达林算法、状态变量设计法等设计方法及其各种改进算法。重点突出计算机控制系统输入输出通道接口的设计方法和典型控制系统的设计案例与实现方法等。

python的requests库全部教程_python的库requests教程

标签:requests是python的第三方库,号称:Requests: HTTP for Humans中文快速教程在这:http://cn.python-requests.org/zh_CN/latest/看完之后有点迷惑,不知道怎么用,看了一下源码,发现#官冈文档中第一条就是>>> r = requests.get(‘https://github.com/timeline.j...

weixin_39702483的博客 176

Python 3安装requests库的详细教程

通过本文的介绍,你已经掌握了如何在 Python 3 环境中安装requests库,并了解了其基本使用方法。requests是一个非常强大的 HTTP 库,能够满足大多数网络请求的需求。希望本文能帮助你更好地使用requests。

加入“Super Entity”,与全能开发团队共探AI智能体与数字人项目,开启前沿技术之旅。 9357

全网最全!Python爬虫requests库教程(附案例)_python requests(1)

外链图片转存中…(img-APHqxBwp-1713758573870)][外链图片转存中…(img-YtHlKnPk-1713758573871)][外链图片转存中…(img-Xu00P9G0-1713758573871)][外链图片转存中…(img-LW67I1Ce-1713758573872)]

2401_84009529的博客 1326

Python Requests库教程

Requests 是一个基于 Python 编写的 HTTP 库,它构建在 urllib 之上,提供了更加简洁易用的 API。调用各类接口发送 GET/POST 等 HTTP 请求进行接口自动化测试爬取网页数据。

qq_46362865的博客 244

python requests 下载教程_《python下载requests库教程》 如何在python中安装requests

python requests怎么安装requests下载下来是个压缩包吧,解压以后打开,里面是不是有个叫setup.py的文件?进入windows命令提示符,然后切换到解压目录,执行> python setup.py install如何在python中安装requestspython的一种包安装方法就是使用pip这里可以用pip install requests 就可以安装requests...

weixin_39685674的博客 7500
上一篇: Python教程:高级特性
下一篇: python教程:Urllib库的基本使用
Python热爱者
博客等级 码龄7年 3053粉丝 1330原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值