本次爬取內(nèi)容就選取章節(jié)名和章節(jié)鏈接作為舉例
url:http://www.xbiquge.la/0/215/
數(shù)據(jù)庫操作的基本方法:
1):連接數(shù)據(jù)庫
2):獲取數(shù)據(jù)庫游標(biāo)
3):執(zhí)行sql語句
4):斷開數(shù)據(jù)庫連接
# 連接數(shù)據(jù)庫,參數(shù)包括IP、用戶名、密碼、對應(yīng)的庫名
connect = pymysql.connect('localhost', 'root', 'gui2019', 'python')
# 數(shù)據(jù)庫游標(biāo)
course = connect.cursor()
# 插入語句
sql = "INSERT INTO kongfu values(default, '%s', '%s') " % (title_name, newUrl)
try:
print("正在寫入數(shù)據(jù) ---->>>>: ", title_name)
course.execute(sql)
connect.commit()
except Exception as e:
print('數(shù)據(jù)寫入失敗!', e)
connect.rollback()
connect.close()
完整代碼如下:
要運行下面的代碼需要現(xiàn)在mysql創(chuàng)建python數(shù)據(jù)庫,kongfu表。 表結(jié)構(gòu)如下圖:
# 引入第三方庫
import requests
import re
import pymysql
def get_data():
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36'
}
# 小說目錄URL
url = 'http://www.xbiquge.la/0/215/'
html = requests.get(url, headers=headers).content.decode('utf-8')
pat = r"
(.*?)
"
list = re.findall(pat, html)
return list
def db_connect(list):
for i in list:
title_url = i[0]
title_name = i[1]
newUrl = 'http://www.xbiquge.la' + title_url
# 連接數(shù)據(jù)庫,參數(shù)包括IP、用戶名、密碼、對應(yīng)的庫名
connect = pymysql.connect('localhost', 'root', 'gui2019', 'python')
# 數(shù)據(jù)庫游標(biāo)
course = connect.cursor()
# 插入語句
sql = "INSERT INTO kongfu values(default, '%s', '%s') " % (title_name, newUrl)
try:
print("正在寫入數(shù)據(jù) ---->>>>: ", title_name)
course.execute(sql)
connect.commit()
except Exception as e:
print('數(shù)據(jù)寫入失敗!', e)
connect.rollback()
connect.close()
def main():
list = get_data()
db_connect(list)
if __name__ == '__main__':
main()
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯(lián)系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
