這次作業(yè)總的而言就是一個理解代碼,修改代碼的過程。
老師給出的代碼中,第一個函數(shù)download()是用來下載界面的html的。
第二個函數(shù)crawled_links()使用了遍歷算法,把其中所有的內(nèi)鏈遍歷了以便。
第三個函數(shù)也通過遍歷來實現(xiàn)了標題和文章內(nèi)容的爬取,并進行了一定的清洗工作,最后存儲到了本地。
該爬蟲總體的思路是:
- 先調(diào)用所需要的包
- 設計一套函數(shù),用來訪問網(wǎng)站,并抓取網(wǎng)站中的HTML文件
- 如果需要抓取該網(wǎng)站相關的鏈接網(wǎng)站,建立一套遍歷算法,利用前面設計好的一套函數(shù)抓取HTML中的url地址。
- 對抓取所有的鏈接通過調(diào)用函數(shù),抓取HTML文件中需要的內(nèi)容。
- 對抓取的內(nèi)容進行清洗保存
我需要爬取的網(wǎng)頁不需要爬取鏈接,只需要爬取當前界面的標題和內(nèi)容,所以,對給出的爬蟲做出了簡化。
下面是我進行修改過的爬蟲:
import os
import time
import urllib2
import urlparse
from bs4 import BeautifulSoup
def download(url,retry=2):#定義一個下載頁面的函數(shù)
print"downlanding: ",url
header = {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.98 Safari/537.36'
}#可以自由設置,相當于網(wǎng)名
try:
request = urllib2.Request(url,headers=header)#相當于輸入網(wǎng)址并輸入自己的登錄名
html = urllib2.urlopen(request).read()#抓取這個網(wǎng)頁的html文件
except urllib2.URLError as e:#服務器不存在(例如鏈接打不開,url鏈接寫錯了)
print "downland error: ", e.reason #輸出異常原因
html = None#返回空值
if retry > 0:#還有重試次數(shù),繼續(xù)嘗試爬取
if hasattr(e, 'code') and 500 <= e.code < 600:#錯誤碼范圍,只有在鏈接打不開的情況下才重新爬取,而鏈接寫錯了則不重新爬取。
print e.code
return dowland(url,retry -1)
time.sleep(1)#等待1s,避免對網(wǎng)站造成沉重負擔,甚至對網(wǎng)站造成嚴重傷害或直接把網(wǎng)站拖垮
return html
def crawled_page(PageUrl):#爬取鏈接中的標題和正文部分,并保存到本地
html = download(PageUrl)
soup = BeautifulSoup(html,"html.parser")
title = soup.find('h1', {'class': 'title'}).text#返回class屬性為title的h1標簽,并且只包含文字。
content = soup.find('div', {'class': 'show-content'}).text#返回class屬性為show-content的div標簽,并且只包含文字。
if os.path.exists('spider_res/') == False: #檢查保存文件的地址
os.mkdir('spider_res')#創(chuàng)建一個目錄
file_name = 'spider_res/' + title + '.txt'#保存的文件名及文件格式
file = open('spider_res/' + title + '.txt', 'wb') #寫文件
content = unicode(content).encode('utf-8', errors='ignore')#用UTF-8實現(xiàn)Unicode,并消除轉義字符
file.write(content)
file.close()
調(diào)用函數(shù)
crawled_page("http://www.lxweimin.com/p/1ea730c97aae")
運行該爬蟲,得到結果:
downlanding: [http://www.lxweimin.com/p/1ea730c97aae](http://www.lxweimin.com/p/1ea730c97aae)
以及該txt文件