根据Scrapy联行号爬虫/Mysql联行号数据库爬到的数据库做的一个小程序。

它的特殊之处在于,是我用ChatGPT写的一个网页,不过总体来看已经满足了我的要求。

我把它放在我阿里云买的季抛的学生机上了,因为是季抛,所以不怕IP泄露,不过也没人无聊到去打它吧。

地址:http://47.115.226.235/

好像是基于Bootstrap的自适应页面,手机端也可以访问哦。

ChatGPT帮我写的代码也放在这里

前端

index.html

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>联行号查询</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
   <script src="script.js"></script>
  <style>
    th {
        background-color: #F5F5F5;
        font-size: 18px;
    }
    h1 {
        color: #6c757d; 
        font-family: 'Helvetica Neue', sans-serif;
        font-size: 24px;
    }
  </style>

</head>
<body>
  <div class="container">
      <h1 style="margin-top: 10px; margin-bottom: 15px;">联行号查询</h1>
    <div class="row">
      <div class="col-sm-4">
        <input type="text" class="form-control" id="s1" placeholder="请输入关键词一(选填)">
      </div>
      <div class="col-sm-4">
        <input type="text" class="form-control" id="s2" placeholder="请输入关键词二(选填)">
      </div>
      <div class="col-sm-4">
        <input type="text" class="form-control" id="s3" placeholder="请输入关键词三(选填)">
      </div>
    </div>
    <div class="row">
      <div class="col-sm-12 text-center">
        <button type="submit" class="btn btn-primary" id="submit-btn" onclick="sendRequest()" style="margin-top: 4px; margin-bottom: 4px;">查询</button>
        <button type="submit" class="btn btn-primary" id="submit-btn" onclick="clearFields()" style="margin-top: 4px; margin-bottom: 4px;">重置</button>  
      </div>
    </div>
    <div class="row">
      <div class="col-sm-12">
        <table class="table table-hover">
          <thead>
            <tr>
              <th>城市</th>
              <th>银行</th>
              <th>名称</th>
              <th>行号</th>
            </tr>
          </thead>
          <tbody id="table-body">
          </tbody>
        </table>
      </div>
    </div>
  </div>
<script>
        const myInput1 = document.querySelector("#s1");
        const myInput2 = document.querySelector("#s2");
        const myInput3 = document.querySelector("#s3");
        myInput1.addEventListener("keyup", function(event) {
        if (event.key === "Enter" && myInput1.value.trim() !== "") {
        sendRequest();
  }});
        myInput2.addEventListener("keyup", function(event) {
        if (event.key === "Enter" && myInput2.value.trim() !== "") {
        sendRequest();
  }});
        myInput3.addEventListener("keyup", function(event) {
        if (event.key === "Enter" && myInput3.value.trim() !== "") {
        sendRequest();
  }});
</script>
<script type="text/javascript">
		function clearFields() {
			document.getElementById("s1").value = "";
			document.getElementById("s2").value = "";
			document.getElementById("s3").value = "";
			
			var tableBody = document.getElementById("table-body");
			while (tableBody.firstChild) {
				tableBody.removeChild(tableBody.firstChild);
			}
		}
</script>
</body>
</html>

script.js

function sendRequest() {
  // 获取输入的参数
  const s1 = document.getElementById("s1").value;
  const s2 = document.getElementById("s2").value;
  const s3 = document.getElementById("s3").value;

  // 构建 URL
  const sList = [s1,s2,s3];
  const filteredList = sList.filter(item => item !== '' && item !== null && item !== undefined && item !== 0);
  if (filteredList.length==0){alert("HTTP error! Status: 403\n请至少输入一个关键词!")}else{
  let url;
  if (filteredList.length==3){
    url = `http://47.115.226.235:8001/query?s1=${filteredList[0]}&s2=${filteredList[1]}&s3=${filteredList[2]}`;
  } else if (filteredList.length==2){
    url = `http://47.115.226.235:8001/query?s1=${filteredList[0]}&s2=${filteredList[1]}`;
  } else if (filteredList.length==1){
    url = `http://47.115.226.235:8001/query?s1=${filteredList[0]}`;
  }
  

  // 发送 GET 请求
  fetch(url, {method:'GET'})
  .then(response => {
    if (response.ok) {
      return response.json()
    }
    else{
      console.log(`HTTP error! Status: 403\n输入错误!只支持纯汉字!`);
      alert(`HTTP error! Status: 403\n输入错误!只支持纯汉字!`);
      throw new Error(`HTTP error! Status: 403\n输入错误!只支持纯汉字!`);
    }
    })
     // 解析响应为 JSON 格式
    .then(data => {
      if (data['data']=='查询结果为空!'){
        console.log(`HTTP error! Status: 404\n未获取到相关数据!`);
        alert(`HTTP error! Status: 404\n未获取到相关数据!`);
        throw new Error(`HTTP error! Status: 404\n未获取到相关数据!`);
      }
      else {
      // 清空表格
      const tableBody = document.querySelector("#table-body");
      tableBody.innerHTML = "";

      // 将 data 列表添加到表格中
      data['data'].forEach(item => {
        const row = tableBody.insertRow();
        row.insertCell().textContent = item[0];
        row.insertCell().textContent = item[1];
        row.insertCell().textContent = item[2];
        row.insertCell().textContent = item[3];
      });
    }})
    .catch(error => console.error(error));}
}

style.css

就是Bootstrap v3.3.7,只是我为了网速而把它本地化了。

原链接地址:https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css

后端

后端是我自己瞎写的,不如ChatGPT

app.py

from fastapi import FastAPI, HTTPException, status
import uvicorn, pymysql, re
from typing import Optional
from fastapi.responses import JSONResponse
from starlette.middleware.cors import CORSMiddleware

def check_regx(s):
    exception = HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail=f'输入错误!只支持纯汉字!')
    if s==None:
        return ''
    elif re.search(r'[\u4e00-\u9fa5]+', s)==None:
        raise exception
    elif re.search(r'[\u4e00-\u9fa5]+', s).group()==s:
        return s
    else:
        raise exception

app = FastAPI()
origins = ["http://47.115.226.235"]

app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
) 

@app.get('/query')
def query(s1:Optional[str]=None,s2:Optional[str]=None,s3:Optional[str]=None):
    s1 = check_regx(s1)
    s2 = check_regx(s2)
    s3 = check_regx(s3)
    connetion = pymysql.Connect(
                                host='******',
                                port=******,
                                user='******',
                                password='******',
                                db='******'
                            )

    with connetion:
        cursor = connetion.cursor()
        sql = f"""SELECT 
                        c.name AS city, b.name AS bank, l.bankname, l.hanghao
                    FROM
                        lhhdata AS l
                            JOIN
                        bankdata AS b ON l.bank_id = b.bank_id
                            JOIN
                        citydata AS c ON l.area_id = c.id
                    WHERE
                        l.bankname LIKE '%{s1}%{s2}%{s3}%'
                    LIMIT 100"""
        cursor.execute(sql)
        result = cursor.fetchall()
        if len(result)==0:
            r = {'status':'failed', 'data':'查询结果为空!'}
        else:
            r = {'status':'success', 'total': len(result), 'data': result}
        return JSONResponse(r,headers={'content-type': 'application/json; charset=utf-8'})




if __name__ == '__main__':
    uvicorn.run('app:app', host='******', port=******, reload=False, workers=1)