為啥存不到數據庫呢?正常打印輸出都沒問題的...

#-*- conding:utf-8 -*-
import requests,re,pymysql
from pyquery import PyQuery as pq


url_index = ['http://finance.eastmoney.com/news/cgnjj_{}.html'.format(pages) for pages in range(1,2)]

def index_content(url_index,title=0,time=0):
#print('起始頁:' + url_index)
index_req = requests.get(url_index,timeout = 10)
index_req.encoding = 'utf-8'
index_content = index_req.text
content_url = re.findall('<div class="text text-no-img">.*?<p class="title">.*?<a href="(.*?)" target="_blank">',index_content,re.S)
title = re.search('<p class="title">.*?<a href=".*?" target="_blank">(.*?)</a>',index_content,re.S).group(1)
time = re.search('<p class="time">(.*?)</p>',index_content,re.S).group(1).replace("年", "-").replace("月", "-").replace("日", "")
#time = time_content
#re.sub(".", "", title)
#print('標題:' + title)
#print('時間:' + time)
return content_url

def content(content_url):
content_req = requests.get(content_url,timeout = 10)
content_req.encoding = 'utf-8'
content = content_req.text
title = re.search('<h1>(.*?)</h1>',content,re.S).group(1)
time = re.search('<div class="time">(.*?)</div>',content,re.S).group(1).replace("年", "-").replace("月", "-").replace("日", "")
source = re.search('<div class="source">.*?<span>來源:</span>(.*?)</div>',content,re.S).group(1)
content_content = re.search('<!--文章主體-->(.*?)<!--責任編輯-->',content,re.S).group(1)
pic = re.findall('''.*?src="https://z1.dfcfw.com(.*?)"''',content_content,re.S)#.sub('.*?same.*?','',content_content)
content_body = {'title:':title,
'time:':time,
'source:':source,
'content:':content_content,
'pic:':pic

}
# print('網址:' + content_url)
# print ('標題:' + title)
# print ('時間:' + time)
# print ('來源:' + source)
# print ('內容:' + content_content )
# print (pic)
#print(content_body)
return content_body

def save_sql(content_body):
try:
db = pymysql.connect("localhost","root","root","test" )
cursor = db.cursor()
sql = """INSERT INTO test(title,source_time, source, content_body, pageurl,pic)VALUES (title,time,source,content_content,content_url,pic)"""
# 執行 sql 語句
cursor.execute(sql)
# 提交到數據庫執行
db.commit()
except:
# 如果發生錯誤則回滾
db.rollback()
# 關閉數據庫連接
db.close()

for url_list in url_index:
index_content(url_list,title=0,time=0)
for con_url in content_url:
con = content(con_url)
#print(con)
save_sql(con)
已邀請:

飛來橫犬

贊同來自:

沒有異常信息嗎?

張含韻微博

贊同來自:

sql = """INSERT INTO test(title,source_time, source, content_body, pageurl,pic)VALUES (title,time,source,content_content,content_url,pic)"""
你解析的信息呢?

微博會員

贊同來自:

source 是 sql 關鍵字吧

李菁菁微博

贊同來自:

sql = """INSERT INTO test(title,source_time, source, content_body, pageurl,pic)VALUES (%s,%s,%s,%s,%s,%s)"""
# 執行 sql 語句
cursor.execute(sql, (title,time,source,content_content,content_url,pic))

夢璟saya

贊同來自:

except:
# 如果發生錯誤則回滾
db.rollback()

except Exception as e:
print(e)
db.rollback()

我猜樓主直接從 runoob 學的

要回復問題請先登錄註冊