close

這次要做的內容是:

將爬好的內容導入自己的線上Mysql資料庫

首先登入進自己的線上資料庫

進入後創建一個table

我命名為test2

73.PNG

 

 

 

 

 

 

 

 

 

 

 

 

連結上資料庫

下面為整合先前四個抓取資料的程式

最後在連接上資料庫將資料寫入

 

from urllib.request import urlopen
import pymysql
from urllib.error import HTTPError
import re
from urllib import request                
from bs4 import BeautifulSoup             
from urllib.parse import urlparse         #導入函數

url = 'https://www.urcosme.com/reviews/1100153'   #選擇網址
user_agent = 'Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.15) Gecko/20110303 Firefox/3.6.15'
headers = {'User-Agent':user_agent}
data_res = request.Request(url=url,headers=headers)
data = request.urlopen(data_res)
data = data.read().decode('utf-8')
sp = BeautifulSoup(data, "lxml")

#以下為標籤
title = sp.findAll("span",{"itemprop":"name"})
tt = []
for t in title:
    tt.append(t)

try:
    ttt = tt[4].text
except:
    ttt = tt[1].text
    
print('標籤:',ttt)  
    
#以下為主圖片
print('主圖片連結:')
img1 = sp.find("div",{"class":"main-image"}).findAll("img", src = re.compile("\/review_image\/"))
img2 = sp.find("div",{"class":"main-image"}).findAll("img", src = re.compile("\/product_image\/"))
for img in img1:
    print(img['src'])
for img in img2:
    print(img['src'])
imgg = img['src']
#以下為內文
print('內文:')
contents = sp.findAll("div",{"class":"review-content"})
for content in contents:
  print(content.text)
ct = content.text

#以下為內文圖片
print('內文圖片:')
c_img1 = sp.find("div",{"class":"review-content"}).findAll("img", src = re.compile("\/review_image\/"))
cc_img = []
if c_img1 != []: #由於上面的程式就會尋找\/review_image\/,所以在這邊就要先確認是否有找到資料
    for c_img in c_img1:
        cc_img.append(c_img['src'])
    print(str(cc_img[:]).replace("["," ").replace("]"," ").replace("'"," ").replace(", "," "))  #先轉成str 再用replace把額外的符號都換成空白
else:
    print('無圖片')
ci = str(cc_img[:]).replace("["," ").replace("]"," ").replace("'"," ").replace(", "," ")




#以下開始連結資料庫


conn = pymysql.connect(                   #資料庫內容請根據自己的資料庫自行設定
host='xxxxxxxxxxxx',
user='xxxxxxxxxx',
passwd='xxxxxxxxx',
database='xxxxxxxxx',
charset='utf8',)                          #讓資料庫能存取中文

cur = conn.cursor()
cur.execute('INSERT INTO `test2` (`標籤名稱`, `主圖片`, `內文`, `內文圖片`)values("%s","%s","%s","%s")'%(ttt,imgg,ct,ci))


conn.commit()  
conn.close()                              #記得要關閉連線

  

 

要注意的地方:

charset='utf8' 讓資料庫能正確存取中文

準備的欄位 跟 要存入的值  數量要對應到

內文圖片的部分,希望資料庫裡面不要有多餘的符號,故轉換成str,再用replace的方式把格式清理乾淨

 

下面是我們成功執行的結果:

74.PNG

 

 

 

接下來的目標:

1.讓程式爬出該商品分類的所有心得文章網址

2.將爬文的每個文章網址放進上面的連接資料庫程式,將爬出的資料存進資料庫

3.讓程式過濾掉重複的內容

4.若爬取會中斷,則降速爬取,甚至定時變換偽裝

5.寫一個主程式選單,根據網站的分類,讓使用者選擇要爬取的分類

 

arrow
arrow
    全站熱搜

    ivankao 發表在 痞客邦 留言(0) 人氣()