這是我自己在學習python 3爬蟲時的小筆記,做備忘用,難免會有一些錯誤和疏漏,望指正~~~
Python 3 爬蟲學習筆記 (一)
Python 3 爬蟲學習筆記 (二)
Python 3 爬蟲學習筆記 (三)
Python 3 爬蟲學習筆記 (五)
Python 3 爬蟲學習筆記 (六)
五 數(shù)據(jù)庫存儲爬取的信息(MySQL)
爬取到的數(shù)據(jù)為了更好地進行分析利用,而之前將爬取得數(shù)據(jù)存放在txt文件中后期處理起來會比較麻煩,很不方便,如果數(shù)據(jù)量比較大的情況下,查找更加麻煩,所以我們通常會把爬取的數(shù)據(jù)存儲到數(shù)據(jù)庫中便于后期分析利用。
這里,數(shù)據(jù)庫選擇MySQL,采用pymysql這個第三方庫來處理python和mysql數(shù)據(jù)庫的存取,python連接mysql數(shù)據(jù)庫的配置信息
db_config ={
'host': '127.0.0.1',
'port': 3306,
'user': 'root',
'password': '',
'db': 'pytest',
'charset': 'utf8'
}
以爬取簡書首頁文章標題以及url為例,先分析抓取目標信息,

Paste_Image.png
如上圖,文章題目在a標簽中,且url(href)只含有后半部分,所以在存儲的時候,最好把它補全。
mysql:新建一個數(shù)據(jù)庫pytest,建立一張名為titles的表,表中字段分別為id(int自增),title(varchar),url(varchar),如下:

Paste_Image.png
進行數(shù)據(jù)庫操作的思路為:獲得數(shù)據(jù)庫連接(connection)->獲得游標(cursor)->執(zhí)行sql語句(execute)->事物提交(commit)->關閉數(shù)據(jù)據(jù)庫連接(close),具體代碼實現(xiàn)如下:
# -*- coding:utf-8 -*-
from urllib import request
from bs4 import BeautifulSoup
import pymysql
# mysql連接信息(字典形式)
db_config ={
'host': '127.0.0.1',
'port': 3306,
'user': 'root',
'password': '',
'db': 'pytest',
'charset': 'utf8'
}
# 獲得數(shù)據(jù)庫連接
connection = pymysql.connect(**db_config)
# 數(shù)據(jù)庫配置,獲得連接(參數(shù)方式)
# connection = pymysql.connect(host='127.0.0.1',
# port=3306,
# user='root',
# password='',
# db='pytest',
# charset='utf8')
url = r'http://www.itdecent.cn/'
# 模擬瀏覽器頭
headers = {
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36'
}
page = request.Request(url, headers=headers)
page_info = request.urlopen(page).read().decode('utf-8')
soup = BeautifulSoup(page_info, 'html.parser')
urls = soup.find_all('a', 'title')
try:
# 獲得數(shù)據(jù)庫游標
with connection.cursor() as cursor:
sql = 'insert into titles(title, url) values(%s, %s)'
for u in urls:
# 執(zhí)行sql語句
cursor.execute(sql, (u.string, r'http://www.itdecent.cn'+u.attrs['href']))
# 事務提交
connection.commit()
finally:
# 關閉數(shù)據(jù)庫連接
connection.close()
代碼執(zhí)行結果:

Paste_Image.png