最近在學習網(wǎng)絡爬蟲,完成了一個比較簡單的python網(wǎng)絡爬蟲。首先為什么要用爬蟲爬取信息呢,當然是因為要比人去收集更高效。

網(wǎng)絡爬蟲,可以理解為自動幫你在網(wǎng)絡上收集數(shù)據(jù)的機器人。

  網(wǎng)絡爬蟲簡單可以大致分三個步驟:

    第一步要獲取數(shù)據(jù),

    第二步對數(shù)據(jù)進行處理,

    第三步要儲存數(shù)據(jù)。

  獲取數(shù)據(jù)的時候這里我用到了python的urllib標準庫,它是python中非常方便抓取網(wǎng)頁內(nèi)容的一個模塊。

  具體為:

  這里我要爬取的是電影天堂一個電影頁面的電影名稱,日期等數(shù)據(jù)。

1 from urllib import request
2 def get_data ( ):
3 url=/http://www.dytt8.net/html/gndy/dyzz/list_23_1.html/
4 headers={/User-Agent/: / Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36/ }
5 req=request.Request(url, headers=headers)
6 response=request.urlopen(req)
7 # print (type(response)) #響應對象的類型
8 # print(response.getcode()) #響應狀態(tài)碼
9 # print(response.info())
10 if response.getcode() == 200:
11 data=response.read()#讀取響應的結(jié)果
12 data =str(data,encoding=/gb2312/)
13 #print(data)
14 #將數(shù)據(jù)寫入文件中
15 with open (/index.html/,mode=/w/,encoding=/gb2312/) as f:
16 f.write(data)

    這里的headers是一個參數(shù),就是你的瀏覽器在訪問服務器的時候,會讓服務器知道你的瀏覽器的一些信息,還有操作系統(tǒng)等信息。if 函數(shù)來判斷當網(wǎng)站成功響應的時候,會返回一個200.這時候讀取響應的數(shù)據(jù)結(jié)果,就是網(wǎng)頁的代碼。這里我做了一個字符串轉(zhuǎn)化處理,根據(jù)網(wǎng)頁代碼顯示編碼為gb2312,所以這時候只要將encoding設(shè)置為gb2312就可以了。

    

1 
2
3
4
5
6
7

根據(jù)上面的網(wǎng)頁代碼,charset為gb2312判斷�?! ?/p>

    當我們存取了�(wǎng)頁數(shù)�(jù)后,�(fā)�(xiàn)它還是html格式�,而且有很多html,css的代�,但是我們只想要其中的文字信�,這時候怎么辦呢�

    這時候就要用到一個強大的�(shù)�(jù)處理模塊,beautifusoup4,俗稱美味湯。安裝好這個模塊后。我們就可以對我們的html文件做進一步的處理,提取我們需要的信息�

   

1 from urllib import request
2 from bs4 import BeautifulSoup
3 def get_data ( ):
4 url=/http://www.dytt8.net/html/gndy/dyzz/list_23_1.html/
5 headers={/User-Agent/: / Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36/ }
6 req=request.Request(url, headers=headers)
7 response=request.urlopen(req)
8 # print (type(response)) #響應對象的類�
9 # print(response.getcode()) #響應狀�(tài)�
10 # print(response.info())
11 if response.getcode() == 200:
12 data=response.read()#讀取響應的�(jié)�
13 data =str(data,encoding=/gb2312/)
14 #print(data)
15 #將數(shù)�(jù)寫入文件�
16 with open (/index.html/,mode=/w/,encoding=/gb2312/) as f:
17 f.write(data)
18 def parse_data():
19 with open (/index.html/,mode=/r/,encoding=/gb2312/) as f:
20 html = f.read()
21 bs = BeautifulSoup(html,/html.parser/)
22 metas = bs.select("[class~=ulink]")
23 date = bs.select("[color=#8F8C89]")
24 i=0
25 while i < 25:
26 print(metas[i].get_text())
27 print(date[i].get_text())
28 i=i+1
29
30
31
32
33 if __name__ == /__main__/:
34 #get_data()
35 parse_data()

?

  這里我們用到了美味湯中的CSS選擇器功�,就是只把我們想要的信息選擇處來,根�(jù)�(wǎng)頁代�,發(fā)�(xiàn)class等于ulink的時候后面跟著的信息是我們需要的。還有color=#8F8C89也是我們需要的。使用select方法,將選中的信息篩選出�。最終結(jié)果:

點擊0是因為網(wǎng)站顯示就�0,估計是�(wǎng)站的問題。這樣我們就得到了電影信息以及發(fā)布的時間信息。后面還有很�。根�(jù)這次簡單爬蟲的實�(xiàn),我�(fā)�(xiàn)web爬蟲除了你要懂python的知識之�,對于html,CSS等前端知識你也要有一定了�。爬蟲是模擬人去收集�(wǎng)站數(shù)�(jù)�,有些網(wǎng)站以及建立了反爬蟲技�(shù)。所以爬蟲的技�(shù)也在不斷更新�

?