者:蒋蜀黍,Python爱好者社区专栏作者
网址:https://mp.weixin.qq.com/s/tfWsiy_LxQSJKUAvB49U0g
1、概览
1.1、实例引入
# 引入Requests库 import requests # 发起GET请求 response=requests.get('https://www.baidu.com/') # 查看响应类型 requests.models.Response print(type(response)) # 输出状态码 print(response.status_code) # 输出响应内容类型 text print(type(response.text)) # 输出响应内容 print(response.text) # 输出cookies print(response.cookies)
1.2、各种请求方式
import requests # 发起POST请求 requests.post('http://httpbin.org/post') # 发起PUT请求 requests.put('http://httpbin.org/put') # 发起DELETE请求 requests.delete('http://httpbin.org/delete') # 发送HEAD请求 requests.head('http://httpbin.org/get') # 发送OPTION请求 requests.options('http://httpbin.org/get')
2、请求
2.1 、基本GET请求
2.1.1、基本写法
import requests response=requests.get('http://httpbin.org/get') print(response.text)
2.1.2、带参数的GET请求
import requests response=requests.get('http://httpbin.org/get?name=jyx&age=18') print(response.text)
2.1.3、带参数的GET请求(2)
import requests # 分装GET请求参数 param={'name':'jyx','age':19} # 设置GET请求参数(Params) response=requests.get('http://httpbin.org/get',params=param) print(response.text)
2.1.4、解析json
import requests response=requests.get('http://httpbin.org/get') # 获取响应内容 print(type(response.text)) # 如果响应内容是json,就将其转为json print(response.json()) # 输出的是字典类型 print(type(response.json()))
2.1.5、获取二进制数据
import requests response=requests.get('http://github.com/favicon.ico') # str,bytes print(type(response.text),type(response.content)) # 输出响应的文本内容 print(response.text) # 输出响应的二进制内容 print(response.content) # 下载二进制数据到本地 with open('favicon.ico','wb') as f: f.write(response.content) f.close()
2.1.6、添加headers
import requests # 设置User-Agent浏览器信息 headers={ "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36" } # 设置请求头信息 response=requests.get('https://www.zhihu.com/explore',headers=headers) print(response.text)
2.2、基本POST请求
import requests # 设置传入post表单信息 data={ 'name':'jyx', 'age':18} # 设置请求头信息 headers={ "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36" } # 设置请求头信息和POST请求参数(data) response=requests.post('http://httpbin.org/post', data=data, headers=headers) print(response.text)
3、响应
3.1 response属性
import requests response=requests.get('http://www.jianshu.com/') # 获取响应状态码 print(type(response.status_code),response.status_code) # 获取响应头信息 print(type(response.headers),response.headers) # 获取响应头中的cookies print(type(response.cookies),response.cookies) # 获取访问的url print(type(response.url),response.url) # 获取访问的历史记录 print(type(response.history),response.history)
3.2、 状态码判断
import requests response=requests.get('http://www.jianshu.com/404.html') # 使用request内置的字母判断状态码 if not response.status_code==requests.codes.ok: print('404-1') response=requests.get('http://www.jianshu.com') # 使用状态码数字判断 if not response.status_code==200: print('404-2')
3.3 requests内置的状态字符
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', '\'), 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', '-'), 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、高级操作
4.1、文件上传
import requests files={'file':open('favicon.ico','rb')} # 往POST请求头中设置文件(files) response=requests.post('http://httpbin.org/post',files=files) print(response.text)
4.2、获取cookies
import requests response=requests.get('https://www.baidu.com') print(response.cookies) for key,value in response.cookies.items(): print(key,'=====',value)
4.3、会话维持
4.3.1、普通请求
import requests requests.get('http://httpbin.org/cookies/set/number/12456') response=requests.get('http://httpbin.org/cookies') # 本质上是两次不同的请求,session不一致 print(response.text)
4.3.2、会话维持请求
import requests # 从Requests中获取session session=requests.session() # 使用seesion去请求保证了请求是同一个session session.get('http://httpbin.org/cookies/set/number/12456') response=session.get('http://httpbin.org/cookies') print(response.text)
4.4、证书验证
4.4.1、无证书访问
import requests response=requests.get('https://www.12306.cn') # 在请求https时,request会进行证书的验证,如果验证失败则会抛出异常 print(response.status_code)
4.4.2、关闭证书验证
import requests # 关闭验证,但是仍然会报出证书警告 response=requests.get('https://www.12306.cn',verify=False) print(response.status_code)
4.4.3、消除关闭证书验证的警告
from requests.packages import urllib3 import requests # 关闭警告 urllib3.disable_warnings() response=requests.get('https://www.12306.cn',verify=False) print(response.status_code)
4.4.4、手动设置证书
import requests # 设置本地证书 response=requests.get('https://www.12306.cn', cert=('/path/server.crt', '/path/key')) print(response.status_code)
4.5、代理设置
4.5.1、设置普通代理
import requests proxies={ "http": "http://127.0.0.1:9743", "https": "https://127.0.0.1:9743", } # 往请求中设置代理(proxies ) response=requests.get("https://www.taobao.com", proxies=proxies) print(response.status_code)
4.5.2、设置带有用户名和密码的代理
import requests proxies={ "http": "http://user:password@127.0.0.1:9743/", } response=requests.get("https://www.taobao.com", proxies=proxies) print(response.status_code)
4.5.3、设置socks代理
pip3 install 'requests[socks]
import requests proxies={ 'http': 'socks5://127.0.0.1:9742', 'https': 'socks5://127.0.0.1:9742' } response=requests.get("https://www.taobao.com", proxies=proxies) print(response.status_code)
4.6、超时设置
import requests from requests.exceptions import ReadTimeout try: # 设置必须在500ms内收到响应,不然或抛出ReadTimeout异常 response=requests.get("http://httpbin.org/get", timeout=0.5) print(response.status_code) except ReadTimeout: print('Timeout')
4.7、认证设置
import requests from requests.auth import HTTPBasicAuth r=requests.get('http://120.27.34.24:9001', auth=HTTPBasicAuth('user', '123')) # r=requests.get('http://120.27.34.24:9001', auth=('user', '123')) print(r.status_code)
4.8、异常处理
事先安装好,pycharm
打开File——>Settings——>Projext——>Project Interpriter
点击加号(图中红圈的地方)
点击红圈中的按钮
选中第一条,点击铅笔,将原来的链接替换为(这里已经替换过了):
https://pypi.tuna.tsinghua.edu.cn/simple/
点击OK后,输入requests-html然后回车
选中requests-html后点击Install Package
等待安装成功,关闭
实例内容:
从某博主的所有文章爬取想要的内容。
实例背景:
从(https://me.csdn.net/weixin_44286745)博主的所有文章获取各文章的标题,时间,阅读量。
from requests_html import HTMLSession
session=HTMLSession()
123
html=session.get("https://me.csdn.net/weixin_44286745").html
12
allBlog=html.xpath("//dl[@class='tab_page_list']")
1
for i in allBlog:
title=i.xpath("dl/dt/h3/a")[0].text
views=i.xpath("//div[@class='tab_page_b_l fl']")[0].text
date=i.xpath("//div[@class='tab_page_b_r fr']")[0].text
print(title +' ' +views +' ' + date )
12345
网页分析:
完整代码:
from requests_html import HTMLSession
session=HTMLSession()
html=session.get("https://me.csdn.net/weixin_44286745").html
allBlog=html.xpath("//dl[@class='tab_page_list']")
for i in allBlog:
title=i.xpath("dl/dt/h3/a")[0].text
views=i.xpath("//div[@class='tab_page_b_l fl']")[0].text
date=i.xpath("//div[@class='tab_page_b_r fr']")[0].text
print(title +' ' +views +' ' + date )
1234567891011121314
喜欢编程的小伙伴可以加一下小编的Q群867067945大家一起交流学习,群里也有专业的大神给你解答难题
言:
很多时候我们部署应用会发现点击其他页面总要重新登录,这种一般是会话问题,系统访问的时候总是无法保持会话,本文主要是通过配置tomcat集群来实现session共享!
1、配置tomcat8080和tomcat9090端口
修改tomcat9090配置文件server.xml
<Server port="9005" shutdown="SHUTDOWN"> <Connector port="9090" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443" /> <Connector port="9009" protocol="AJP/1.3" redirectPort="8443" />
2、设置tomcat集群
修改tomcat的配置文件,打开conf下的server.xml文件,找到下面这一行
<Engine name="Catalina" defaultHost="localhost">
不需要做任何修改,在这一行的下面加入如下代码:
<Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster" channelSendOptions="8"> <Manager className="org.apache.catalina.ha.session.DeltaManager" expireSessionsOnShutdown="false" notifyListenersOnReplication="true"/> <Channel className="org.apache.catalina.tribes.group.GroupChannel"> <Membership className="org.apache.catalina.tribes.membership.McastService" address="228.0.0.4" port="45564" frequency="500" dropTime="3000"/> <Receiver className="org.apache.catalina.tribes.transport.nio.NioReceiver" address="auto" port="4000" autoBind="100" selectorTimeout="5000" maxThreads="6"/> <Sender className="org.apache.catalina.tribes.transport.ReplicationTransmitter"> <Transport className="org.apache.catalina.tribes.transport.nio.PooledParallelSender"/> </Sender> <Interceptor className="org.apache.catalina.tribes.group.interceptors.TcpFailureDetector"/> <Interceptor className="org.apache.catalina.tribes.group.interceptors.MessageDispatch15Interceptor"/> </Channel> <Valve className="org.apache.catalina.ha.tcp.ReplicationValve" filter=""/> <Valve className="org.apache.catalina.ha.session.JvmRouteBinderValve"/> <Deployer className="org.apache.catalina.ha.deploy.FarmWarDeployer" tempDir="/tmp/war-temp/" deployDir="/tmp/war-deploy/" watchDir="/tmp/war-listen/" watchEnabled="false"/> <ClusterListener className="org.apache.catalina.ha.session.JvmRouteSessionIDBinderListener"/> <ClusterListener className="org.apache.catalina.ha.session.ClusterSessionListener"/> </Cluster>
这个就是tomcat自带的集群配置了,在tomcat官方文档中的cluster-howto.html中看到相关注意事项,其中有一条需要注意一下:Make sure your web.xml has the <distributable/> element
很明显是说web项目的web.xml文件中需要有<distributable/>这个元素,所以在引入的web项目中做修改。
3、修改项目
在\tomcat\webapps\下新建testcluster文件夹,testcluster下新建index.jsp获取SessionID
<html> <head> <title>title</title> <meta http-equiv="Content-Type"content="text/html; charset=gb2312"/> </head> <body> ? SessionID:<%=session.getId()%> <BR> SessionIP:<%=request.getServerName()%> <BR> SessionPort:<%=request.getServerPort()%> <% out.println("This is Tomcat Server 8080"); %> ? </body> </html>
testcluster下建立WEB-INF文件夹,在WEB-INF下新建web.xml指向index.jsp和添加<distributable/>元素
<?xml version="1.0" encoding="UTF-8"?> <!-- PublicCMS使用Servlet3.0技术,Web.xml不再是整个工程的入口,config.initializer.*Initializer为工程的入口类,config.*Config为Spring配置 --> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>elearning</display-name> <distributable/> ? <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
注意:由于\conf\content.xml配置了web.xml指向是要放在WEB-INF下,所以web.xml需要放在WEB-INF里面
D:\tomcat集群\tomcat8080\conf\content.xml
<Context> ? <!-- Default set of monitored resources --> <WatchedResource>WEB-INF/web.xml</WatchedResource> ? <!-- Uncomment this to disable session persistence across Tomcat restarts --> <!-- <Manager pathname="" /> --> ? <!-- Uncomment this to enable Comet connection tacking (provides events on session expiration as well as webapp lifecycle) --> <!-- <Valve className="org.apache.catalina.valves.CometConnectionManagerValve" /> --> ? </Context>
4、启动tomcat并测试
启动tomcat:
D:\tomcat集群\tomcat8080\bin\startup.bat
D:\tomcat集群\tomcat9090\bin\startup.bat
测试地址:
http://localhost:8080/testcluster/index.jsp
http://localhost:9090/testcluster/index.jsp
每个浏览器会有不同的SessionID,但同个浏览器访问不同端口所获取的SessionID一致
附:tomcat集群配置参数
以上关于tomcat集群的配置只要在 <Engine> 节点 或者 <Host> 节点内部加上下面的代码即可支持集群化:
<Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"/>
该配置将开启 all-to-all session 复制,并通过 DeltaManager 来复制 session 增量. 采用 all-to-all 方式意味着 session 会被复制到此集群中其他的所有节点. 对于很小的集群,这种方式很适用, 但我们不推荐在较大的集群中使用(有很多 tomcat 节点的情况。例如,几十个节点及以上...). 另外,使用 delta 增量管理器时,即使 某些节点没有部署应用程序,也会复制 session 到所有节点上.
要在较大的集群上进行session复制,需要使用 BackupManager. 此 manager 只复制 session 数据到一个备份节点, 并且只复制到部署了对应应用程序的那些节点. BackupManager的缺点: 经过测试,性能不如 delta manager.
下面是一些重要的默认值:
1. 默认的 Multicast (组播)地址是: 228.0.0.4
2. 默认的 Multicast (组播)端口是: 45564 (端口号和地址组合以后就决定了 cluster 关系,被认为是同一个集群).
3. 默认广播的IP java.net.InetAddress.getLocalHost().getHostAddress() (确保你不是广播到 127.0.0.1, 这是一个常见的错误)
4. 默认的监听复制消息的 TCP 端口是在 4000-4100 范围内第一个可用的server socket。
5. 配置了两个监听器: ClusterSessionListener 和 JvmRouteSessionIDBinderListener
6. 配置了两个拦截器: TcpFailureDetector 和 MessageDispatch15Interceptor
很多人都说写技术类的文章没人看,不管怎样,分享出来起码自己也可以看~
*请认真填写需求信息,我们会在24小时内与您取得联系。