db = pymysql.connect(host = ‘127.0.0.1’,port = 3306,db = ‘db’,user = ‘root’,passwd = ‘root’,charset = ‘utf8’)
创建游标
cursor = db.cursor()
cursor.execute(‘select * from images’)
print(cursor.fetchall())
小驼峰
注释 获取图片列表
def getImagesList(page):
获取斗图网源代码
html = requests.get(‘http://www.doutula.com/photo/list/?page={}’.format(page)).text
正则表达式 通配符 .*? 匹配所有 分组匹配
reg = r’data-original=“(.?)".?alt=”(.*?)"’
增加匹配效率的 S 多行匹配
reg = re.compile(reg,re.S)
imagesList = re.findall(reg,html)
for i in imagesList:
image_url = i[0]
image_title = i[1]
format 字符串格式化 %s
cursor.execute("insert into images(name,imageUrl) values(‘{}’,‘{}’) ".format(image_title,image_url))
print(‘正在保存 %s’%image_title)
db.commit()
range 范围 1<=X<1000
for i in range(1,1001):
print(‘第{}页’.format(i))
getImagesList(i)
效果图

使用的框架是Flask
from flask import Flask
from flask import render_template
from flask import request
import pymysql
404 页面未找到
app = Flask(name)
装饰器
@app.route(‘/’) # route 路由
def index():
return “hello world”
return render_template(‘index.html’)
@app.route(‘/search’)
def search():
接收用户关键字
keyword = request.args.get(‘kw’)
count = request.args.get(‘count’)
cursor.execute(“select * from images where name like ‘%{}%’”.format(keyword))
data = cursor.fetchmany(int(count))
return render_template(‘index.html’,images = data)
程序的入口
if name == ‘main’:
db = pymysql.connect(host=‘127.0.0.1’, port=3306, db=‘db’, user=‘root’, passwd=‘root’, charset=‘utf8’,cursorclass = pymysql.cursors.DictCursor)
创建游标
cursor = db.cursor()
调试模式

感谢每一个认真阅读我文章的人,看着粉丝一路的上涨和关注,礼尚往来总是要有的:
① 2000多本Python电子书(主流和经典的书籍应该都有了)
② Python标准库资料(最全中文版)
③ 项目源码(四五十个有趣且经典的练手项目及源码)
④ Python基础入门、爬虫、web开发、大数据分析方面的视频(适合小白学习)
⑤ Python学习路线图(告别不入流的学习)
网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。
一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!
本文介绍了如何使用Python的pymysql库连接数据库,执行SQL查询,并结合Flask框架展示了一个搜索功能。同时涉及网页爬虫技术,如使用正则表达式提取斗图网图片信息并插入数据库。

被折叠的 条评论
为什么被折叠?



