前言
最近做项目要把新闻的标题,内容,链接提取出来,放入数据库。花了2天半的时间弄这个,踩了一些坑,记录下来。
pymysql连接数据库
# 打开数据库连接
db = pymysql.connect("47.107.41.60","root","密码","wisdomagriculture"
)
# 使用cursor()方法获取操作游标
cursor = db.cursor()
for content in content_list:
print("*"*50)
# print("title"+content["title"])
title = content["title"]
href = content["href"]
# print("0"+href[0])
# print("1"+title[0])
sql = "INSERT INTO news (news_title,news_href,news_time) VALUES (%(title)s,%(href)s,%(time)s)"
print(content)
cursor.execute(sql,content)
db.commit()
db.close()
注意:
- 在插入数据的时候一定要注意,不要插入list[]类型的。
- 在插入字典类型的数据的时候,可以这么写。
sql = "INSERT INTO news (news_title,news_href,news_time) VALUES (%(title)s,%(href)s,%(time)s)"
cursor.execute(sql,content)
- 最后要提交一下
- 正则获取数据的时候
href = re.findall(r"<a href='(.*?)'", content, re.S)[0] if len(re.findall(r"<a href='(.*?)'", content, re.S))>0 else '错误'
职场就像方便面,曲曲折折,三分钟热度,关键是加量不加价。