selenium原理&搭建web服务
selenium原理:
from selenium import webdriver import requests driver = webdriver.Chrome(port=6090) url = "http://www.baidu.com" # driver.get(url) # 上面的driver.get(url)步骤相当于下面的requests.post(server_url, json={"url":url})步骤 server_url = "http://localhost:6090/session/{}/url".format(driver.session_id) requests.post(server_url, json={"url":url})
web开发 :基于web协议,HTTP,WebSocket
客户端:前端(HTML+CSS+JS),Android,iOS,小程序等
服务端:server,后端,提供服务
搭建web服务
一个简单服务器需要有的流程:
搭建服务
监听动作--- 相当于while循环(如每个几秒就检测一次是否有请求)
处理程序
返回数据到套接字,生成一个响应对象
搭建一个简单的web服务:
from wsgiref.simple_server import make_server def app(env, start_response): # env:获取请求相关数据,保存在环境变量里面 # start_response:状态码,header # 状态码(必须为字符串,要大于4个字符), # header(列表类型,列表的元素为元组,元组由两个元素组成,第一个元素相当于字典的key,第二个元素相当于字典的value) start_response("200 OK", [("content-type", "text/plain")]) return [b"hello"] # 返回值要为字节类型 server = make_server("", 6001, app) server.serve_forever()
例子:
class Router: def __init__(self): self.url = {} def route(self, path): def decorator(func): self.url[path] = func func() return decorator def __call__(self, env, start_response): path = env.get("PATH_INFO") if path in self.url: start_response("200 OK", [("content-type", "text/plain")]) return self.url[path]() else: start_response("404 Not Found", [("content-type", "text/plain")]) return [b"404 Not Found"] app_1 = Router() @app_1.route("/login") def login(): yield b"login page" @app_1.route("/") def index(): yield b"index page" @app_1.route("/projects") def projects(): yield b"projects page" server = make_server("", 6001, app_1) server.serve_forever()
也可这样写:
class Route: def __init__(self): self.url_path = { "/login": self.login, "/": self.index, "/projects": self.projects } def app(self, env, start_response): # env: 获取请求的相关数据 # 状态码,header if (env.get("PATH_INFO") not in self.url_path.keys()) or \ (env.get("PATH_INFO") is None) or \ (self.url_path.get(env["PATH_INFO"])(env.get("QUERY_STRING")) is None): start_response("404 not found", [("content-type", "text/plain")]) return [b"not found"] else: start_response("200 ok", [("content-type", "text/plain")]) return self.url_path.get(env["PATH_INFO"])(env.get("QUERY_STRING")) def login(self, request): return [f"login {request}".encode()] def index(self, request): return [f"index {request}".encode()] def projects(self, request): return [f"projects {request}".encode()] server = make_server("", 6001, Route().app) server.serve_forever()