import requests
import re
import pymysql
headers = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36'}
def baidu(company):
url = 'https://www.baidu.com/s?rtt=1&bsst=1&cl=2&tn=news&word=' + company
res = requests.get(url, headers = headers).text
p_href = '<h3 class="c-title">.*?<a href="https://bbs.csdn.net/topics/(.*?)"'
p_title = '<h3 class="c-title">.*?>(.*?)</a>'
p_info = '<p class="c-author">(.*?)</p>'
href = re.findall(p_href, res, re.S)
title = re.findall(p_title, res, re.S)
info = re.findall(p_info, res, re.S)
# 資料清洗及列印輸出
source = []
date = []
for i in range(len(title)):
title[i] = title[i].strip()
title[i] = re.sub('<.*?>', '', title[i])
info[i] = re.sub('<.*?>', '', info[i])
source.append(info[i].split(' ')[0])
date.append(info[i].split(' ')[1])
source[i] = source[i].strip()
date[i] = date[i].strip()
# print(date[i])
for i in range(len(title)):
db = pymysql.connect(host='localhost', port=3306, user='root', password='', database='pachong', charset='utf8')
cur = db.cursor() # 獲取會話指標,用來呼叫SQL陳述句
sql = 'INSERT INTO test(company,title,href,date,source) VALUES (%s,%s,%s,%s,%s)' # 撰寫SQL陳述句
cur.execute(sql, (company, title[i], href[i], date[i],source[i]) # 執行SQL陳述句
db.commit()
cur.close() # 關倍訓話指標
db.close() # 關閉資料庫連接
baidu('阿里巴巴')
提示 invalid syntax 在 db.commit()的位置
uj5u.com熱心網友回復:
錯誤陳述句的上面一行,最后少了一個括號。細心點……uj5u.com熱心網友回復:
謝謝啦,以后會注意的。剛開始學,好多的都還不看不明白轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/65322.html
