python爬蟲練習,爬取資料寫入MySQL資料庫

2021-09-25 06:55:49 字數 1964 閱讀 7632

本次爬取內容就選取章節名和章節鏈結作為舉例

資料庫操作的基本方法:

1):連線資料庫

2):獲取資料庫游標

3):執行sql語句

4):斷開資料庫連線

# 連線資料庫,引數包括ip、使用者名稱、密碼、對應的庫名

connect = pymysql.connect('localhost', 'root', 'gui2019', 'python')

# 資料庫游標

course = connect.cursor()

# 插入語句

sql = "insert into kongfu values(default, '%s', '%s') " % (title_name, newurl)

try:

print("正在寫入資料 ---->>>>: ", title_name)

course.execute(sql)

connect.commit()

except exception as e:

print('資料寫入失敗!', e)

connect.rollback()

connect.close()

執行效果如圖所示:

完整**如下:

要執行下面的**需要現在mysql建立python資料庫,kongfu表。 表結構如下圖:

#  引入第三方庫

import requests

import re

import pymysql

def get_data():

headers =

# **目錄url

url = ''

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 = '' + title_url

# 連線資料庫,引數包括ip、使用者名稱、密碼、對應的庫名

connect = pymysql.connect('localhost', 'root', 'gui2019', 'python')

# 資料庫游標

course = connect.cursor()

# 插入語句

sql = "insert into kongfu values(default, '%s', '%s') " % (title_name, newurl)

try:

print("正在寫入資料 ---->>>>: ", title_name)

course.execute(sql)

connect.commit()

except exception as e:

print('資料寫入失敗!', e)

connect.rollback()

connect.close()

def main():

list = get_data()

db_connect(list)

if __name__ == '__main__':

main()

python爬蟲小練習 小說爬取

import requests from bs4 import beautifulsoup if name main headers 對首頁的頁面資料進行爬取 url page text requests.get url url,headers headers text 在首頁中解析出章節的標題和詳...

Python 爬蟲練習專案 非同步載入爬取

專案 from bs4 import beautifulsoup import requests url prefix infos 獲取單個頁面資料 def getapage url,data none web data requests.get url soup beautifulsoup web...

python爬蟲 爬取貓眼電影資料

定義乙個函式獲取貓眼電影的資料 import requests def main url url html requests.get url text print html if name main main 利用正則匹配,獲得我們想要的資訊 dd i class board index board...