平台商城网站建设,wordpress 还原备份数据库,wordpress 外部链接插件,服装网都有哪些网站第七天 Python项目实操
编者打算开一个python 初学主题的系列文章#xff0c;用于指导想要学习python的同学。关于文章有任何疑问都可以私信作者。对于初学者想在7天内入门Python#xff0c;这是一个紧凑的学习计划。但并不是不可完成的。 学到第7天说明你已经对python有了一…第七天 Python项目实操
编者打算开一个python 初学主题的系列文章用于指导想要学习python的同学。关于文章有任何疑问都可以私信作者。对于初学者想在7天内入门Python这是一个紧凑的学习计划。但并不是不可完成的。 学到第7天说明你已经对python有了一个基本的认识下面通过完成一个小项目来巩固之前几天所学的知识。 接下来我们上干货 编者是一个网文读者常常因为小说需要订阅或者有时候网路不好看不到小说因此选择将小说下载下来保证能过随时随地的阅读。看看这个小项目的效果
接下来你需要熟悉几个词语网页开发flask 框架request 、BeautifulSoup库 源代码我放在**源代码地址** 网页开发: 定义 网页开发是指创建和维护网页的过程。它涵盖了从设计、编写前端代码HTML、CSS、JavaScript到后端开发服务器端代码、数据库交互以及整个网站的部署和维护等一系列工作。网页开发旨在创造用户友好的、功能完善的网站和Web应用。 Flask 框架: 定义 Flask 是一个基于 Python 的轻量级 Web 框架用于构建 Web 应用程序。它提供了一些核心工具如路由、视图函数、模板引擎等使得开发者能够以简洁而灵活的方式构建 Web 应用。Flask 是一个微框架它提供了一些基础的功能但让开发者有更大的自由度选择其他库来满足特定需求。 requests 库: 定义 requests 是一个用于发送 HTTP 请求的 Python 第三方库。它提供了简单而强大的 API用于处理各种类型的请求和响应如 GET、POST 等。requests 库使得在 Python 中进行网络请求变得更加方便可以用于从 Web 服务器获取数据、与 API 交互等场景。 BeautifulSoup 库: 定义 BeautifulSoup 是一个 Python 库用于从 HTML 或 XML 文档中提取数据。它提供了一种方便的方式来搜索文档树、遍历文档树中的元素以及修改文档树。在网页开发中BeautifulSoup 主要用于解析 HTML 页面从中提取结构化的信息例如抓取特定标签的内容、提取链接、或者进行数据挖掘。
在网页开发中通常会使用 Flask 框架来构建 Web 应用的后端同时使用 requests 库来进行与其他服务器的通信获取数据。而在处理获取到的 HTML 页面时可以借助 BeautifulSoup 库进行解析和信息提取。这三者的结合使得开发者能够更轻松地构建和处理 Web 应用。 代码我放在gitee 仓库https://gitee.com/constantine-G/getbook
项目搭建
然后开始我们的项目搭建 使用pycharm 编辑器 创建项目 新建好的干净项目 此时你可以启动这个项目会返回一句话 创建交互页面
创建这样两个文件 网络下载这个文件如果找不到直接到我的仓库下载 index.html 内容 !DOCTYPE html
html langen
headmeta charsetUTF-8titlehello,my world!/title
/head
body
div idappinput idbookName输入书籍、作者名称/inputbutton idswap确认/buttonul iddata-list/ulinput idbdbookName本地书籍/inputbutton idsearch搜索/buttonul idbd-list/ul
/div
{# script src/static/js/common/vue/vue.js/script#}
{# script typetext/javascript src/static/js/common/require/require.min.js/script#}script src/static/js/common/jquery.js/scriptscript src/static/js/index.js/script/body
/htmliondex,js 内容 const person document.getElementById(bookName);
const bdbookName document.getElementById(bdbookName);
$(document).ready(function () {$(#swap).click(function () {$.ajax({type: POST,url: /searchBook,dataType: json,data: {bookName: person.value},success: function (res) {displayData(res);// addListener();},error: function (xhr, status, error) {alert(error);}});});$(#search).click(function () {$.ajax({type: POST,url: /searchBd,dataType: json,data: {bookName: bdbookName.value},success: function (res) {dbdisplayData(res);// addListener();},error: function (xhr, status, error) {alert(error);}});});//
});function addListener(){// 获取列表项元素const listItems document.querySelectorAll(#data-list li);// 为每个列表项添加点击事件listItems.forEach(item {item.addEventListener(click, () {downLoadBook(item)});});
}function addListener(){// 获取列表项元素const listItems document.querySelectorAll(#bd-list li);// 为每个列表项添加点击事件listItems.forEach(item {item.addEventListener(click, () {downLoadBook(item)});});
}
function downLoadBook(event) {$.ajax({type: POST,url: /downLoadBook,dataType: json,data: {book: data},success: function (res) {alert(res);},error: function (xhr, status, error) {alert(error);}});
}
function dbdisplayData(data) {var dataList $(#bd-list);dataList.empty();data.forEach(function (item) {// a href{{ url_for(downLoadBook, idpost[id]) }}Edit/a// var url /downLoadBook item.link;var url /downLoadBook item.bookLink;dataList.append(li item.bookName a href\url\ 下载 /a地址 item.path/li);// dataList.append(li item.bookName /li);});
}function displayData(data) {var dataList $(#data-list);dataList.empty();data.forEach(function (item) {// a href{{ url_for(downLoadBook, idpost[id]) }}Edit/avar url /downLoadBook item.link;dataList.append(li item.name a href\url\下载/a/li);});
}
在app.py 文件中添加一个方法
app.route(/)
def hello_world(): # put applications code herereturn render_template(index.html)
此时再次重启项目并访问 http://127.0.0.1:5000/ 可以看到已经多了一些内容。这是用于一个简单交互的页面。主要是输入想要下载的书籍发起查询然后在下载
完成时的效果
网站后端查询小说
新增一个文件叫book.py 并新增以下内容 主要是点击查询的功能实现 def searchBooklist(bookName):try:# 发送GET请求 http://www.biqu5200.netresponse requests.get(url http://www.biqu5200.net /modules/article/search.php?searchkey bookName, headersheader)response.encoding utf-8# 检查请求是否成功res []bookList []if response.status_code 200:# 如果请求成功获取响应数据soup BeautifulSoup(response.content, html.parser)even_items soup.find_all(tr)# 遍历并打印匹配的元素内容for item in even_items:booklink item.find(a)if booklink ! None and booklink[href] ! None and booklink.text ! None:book {name: booklink.text,link: booklink[href]}bookO {name: booklink.text,link: urlbooklink[href]}res.append(book)# book select(booklink.text)if book None:bookList.append(bookO)# insert(bookList)return reselse:# 如果请求失败打印错误信息print(请求失败状态码, response.status_code)return resexcept requests.exceptions.RequestException as e:# 处理请求异常print(请求异常, e)return res
这个方法是返回一个书籍的列表 接下来实现下载功能 def downLoadBook(bookLink):# 发送GET请求# response requests.get(urlbook[link], headersheader)# 请求数据response getRequsetContent(url/bookLink)if response ! None:# 如果请求成功获取响应数据soup BeautifulSoup(response, html.parser)even_items soup.find_all(dd)bookName soup.find(idinfo).find(h1).textstart time.time()min len(even_items) / (60/second)hour min / 60print(预估时间 str(min) 分钟 str(hour)小时)# 遍历并打印匹配的元素内容# open(bookName.txt, moder)# 读文件# open(demo1/1.txt, modew)# 写文件file open(bookName .txt, modew,encodingutf-8)file open(bookName .txt, modea,encodingutf-8)# 追加ret_message {code: 0, status: successful, msg: 成功,耗时 str(min)}failed []# book select(bookName)try:chapterList []for item in even_items:booklink item.find(a)chapter {bookid: book[id],chapterLink: url booklink[href],chapterName: booklink.text}chapterList.append(chapter)# insertChapter(chapterList)leastchaper for item in even_items:booklink item.find(a)contemxUrl booklink[href]chaper booklink.textleastchaper chaperchaperurl url contemxUrl# 休息1秒time.sleep(second)content getRequsetContent(chaperurl)contentList []if content ! None:soup BeautifulSoup(content, html.parser)chapername soup.find(class_bookname).find(h1).textcontentList.append(chapername \n)pList soup.find(idcontent).find_all(p)contentList []for p in pList:constr p.textif constr.find(请记住本书首发域名。顶点小说手机版阅读网址) ! -1:print(有广告 constr)contentList.append(p.text \n)else:failed.append(chaper)file.writelines(contentList)# update(chaper,url booklink[href])print(完成chaper)upBook Book(book[id],1,os.path.abspath(os.path.dirname(file.__str__())).replace(\\,/),leastchaper,;.join(failed))# updateBook(upBook)print(failed .join(failed))size file.seek(0, os.SEEK_END)end time.time()print(size .join(size))print(time end - start)file.close()return ret_messageexcept Exception as e:# 处理请求异常file.close()print(异常, e)return ret_messageelse:# 如果请求失败打印错误信息print(请求失败状态码, response.status_code)# 公用方法
def getRequsetContent(url):try:# 发送GET请求response requests.get(urlurl, headersheader)response.encoding utf-8# 检查请求是否成功if response.status_code 200:# 如果请求成功获取响应数据return response.contentelse:# 如果请求失败打印错误信息print(请求失败状态码, response.status_code)return Noneexcept requests.exceptions.RequestException as e:# 处理请求异常print(请求异常, e)return None
到此我们的功能就基本完成了。实现了查询数据并选择自己想要的书籍下载有任何疑问请联系我