close

這次會來寫出4個副程式

以下為這次要準備出來的函式

 

副程式:

1.爬出該頁面內的標籤名稱

2.爬出該頁面主圖片

3.爬出該頁面文章內容

4.爬出該頁面文章中圖片

 

首先要先連上對象網站

許多網站會防止python爬蟲獲取信息

所以需經過偽裝才能透過python獲取需要的資料

以下是經過偽裝後獲取信息的方式

(採用bs4模組)

 

 

 
from urllib.request import urlopen          #導入函數
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")        #導入bs4模組
 

 

 

1.爬出該頁面內的標籤名稱

在該網頁按下F12來抓取需要的欄位

 

<span itemprop="name">標籤</span>

先用bs4模組

 

#以下為標籤
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)  

 

上面做了一個例外處理,假如標籤第四欄位沒有內容,就會傳回第二欄位的內容

 

 

 

2.爬出該頁面中的主圖片

在該網頁按下F12來抓取需要的欄位

這是我們找到的訊息

<img alt="" class="img-auto-center" data-image-size="775x280" src="https://dg9ugnb21lig7.cloudfront.net/uploads/review_image/1004581/_775x280_20170222071529.jpg" style="position: relative; left: 0px; top: 0px; width: auto; height: auto; max-width: 775px; max-height: 280px; vertical-align: middle; opacity: 1;">

 

 

#主圖片有兩種連結
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'])

 

該網站主圖片有兩種連結,分新版跟舊版

如果新版沒找的內容,就會跑出舊版的圖片

還可以再優化,但今天先不做

 

 

 

3.爬出該頁面中的內文

在該網頁按下F12來抓取需要的欄位

這是我們找到的訊息

 

<div class="review-content">

內文

</div>

 

#爬網頁中內文
contents = sp.findAll("div",{"class":"review-content"})
for content in contents:
  print(content.text)

 

這裡比較簡單,直接用bs4的模組就會過濾掉不必要的html程式碼

但是出來的內容並不整齊,需之後自行調整

 

 

 

4.爬出該頁面中的內文圖片

在該網頁按下F12來抓取需要的欄位

 

這是我們找到的訊息

<div class="review-content">

內文+包含圖片程式碼

</div>

 

#爬網頁中內文圖片

c_img1 = sp.find("div",{"class":"review-content"}).findAll("img", src = re.compile("\/review_image\/"))
if c_img1 != []:                        #由於上面的程式就會尋找\/review_image\/,所以在這邊就要先確認是否有找到資料
    for c_img in c_img1:
        print(c_img['src'])
else:
    print('無圖片')


 

由於用.text的方式過濾會連圖片的程式碼都過濾掉

所以這次採用深入尋找的方法

並不是所有文章內都會插入圖片,所以做了例外處理,沒圖片的話就會顯示無圖片

arrow
arrow
    全站熱搜

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