前言
最近做項目要把新聞的標題,內容,鏈接提取出來,放入數據庫。花了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 '錯誤'
職場就像方便麪,曲曲折折,三分鐘熱度,關鍵是加量不加價。