課程作業(yè)
- 選擇第二次課程作業(yè)中選中的網(wǎng)址
- 爬取該頁面中的所有可以爬取的元素,至少要求爬取文章主體內(nèi)容
- 可以嘗試用lxml爬取
在完成這節(jié)課的過程中遇到許多問題:
- 環(huán)境問題:電腦安裝的是python 3.x,老師的demo使用python2.7,如何在anaconda中進(jìn)行環(huán)境切換。
在anaconda中切換py2和py3
conda create env_name list of packages
conda create -n py2 python=2.7 pandas
進(jìn)入名為env_name的環(huán)境
source activate env_name
退出當(dāng)前環(huán)境
source deactivate
在windows系統(tǒng)中,使用activate env_name 和 deactivate env_name進(jìn)入和退出
刪除名為env_name的環(huán)境
conda env romove -n env_name
顯示所有環(huán)境
conda env list
使用pip安裝對應(yīng)的模塊:
使用pip安裝相關(guān)模塊時,所有的模塊都被安裝到python3.x目錄下面,網(wǎng)上查了很多資料,還是沒有解決該問題,只好用一個很傻的方法,將python3.x卸載,只使用python2.7,這樣使用pip安裝模塊時,所有模塊會被安裝到python2.7環(huán)境中。jupyter notebook環(huán)境切換:
創(chuàng)建python2.7環(huán)境
conda create -n ipykernel_py2 python=2 ipykernel # 創(chuàng)建Python2環(huán)境
source activate ipykernel_py2 # 進(jìn)入該環(huán)境
python -m ipykernel install --user # 使python2 kernel 在jupyter中新建notebook時顯示閱讀beautifulsoup4文檔:
- BeautifulSoup模塊:第一個參數(shù)應(yīng)該是要被解析的文檔字符串或是文件句柄,第二個參數(shù)用來標(biāo)識怎樣解析文檔.要解析的文檔類型: 目前支持, “html”, “xml”, 和 “html5”
- 從文檔中找到所有<a>標(biāo)簽的鏈接:
for link in soup.find_all('a'):
print link.get('href')
- find_all()與find()用法:
- find_all( name , attrs , recursive , text , **kwargs )
- name 參數(shù),可以查找所有名字為 name 的tag,字符串對象會被自動忽略掉.
- keyword 參數(shù),如果一個指定名字的參數(shù)不是搜索內(nèi)置的參數(shù)名,搜索時會把該參數(shù)當(dāng)作指定名字tag的屬性來搜索,如果包含一個名字為 id 的參數(shù),Beautiful Soup會搜索每個tag的”id”屬性.
- text 參數(shù),通過 text 參數(shù)可以搜搜文檔中的字符串內(nèi)容.與 name 參數(shù)的可選值一樣, text 參數(shù)接受 字符串 , 正則表達(dá)式 , 列表, True
- recursive 參數(shù),調(diào)用tag的 find_all() 方法時,Beautiful Soup會檢索當(dāng)前tag的所有子孫節(jié)點(diǎn),如果只想搜索tag的直接子節(jié)點(diǎn),可以使用參數(shù) recursive=False
- find( name , attrs , recursive , text , **kwargs )
- 區(qū)別:find_all() 方法的返回結(jié)果是值包含一個元素的列表,而find()方法直接返回結(jié)果;find_all() 方法沒有找到目標(biāo)是返回空列表, find() 方法找不到目標(biāo)時,返回 None。
- find_all( name , attrs , recursive , text , **kwargs )
作業(yè)
導(dǎo)入庫
import os ## os模塊包含普遍的操作系統(tǒng)功能
import time ## time時間模塊
import urllib2 ## 可用于頁面下載,身份驗(yàn)證,提交表格等,支持非http協(xié)議
import urlparse ##
from bs4 import BeautifulSoup ## 解析網(wǎng)頁,提供定位內(nèi)容的便捷接口
下載指定頁面的html函數(shù)download
def download(url, retry=2):
"""
下載頁面的函數(shù),會下載完整的頁面信息
:param url: 要下載的url
:param retry: 重試次數(shù)
:reutrn: 原生html
"""
print "downloading:",url
# 設(shè)置header信息,模擬瀏覽器請求
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'
}
try: #爬去可能會失敗,采用try-expect方式來捕獲處理
request = urllib2.Request(url, headers = header)
html = urllib2.urlopen(request).read() #抓取url
# except urllib.error.URLError as e: #異常處理
except urllib2.URLError as e:
print "download error:", e.reason
html = None
if retry > 0: #未超過重試次數(shù),可以繼續(xù)爬取
if hasattr(e, 'code') and 500 <= e.code <600: #錯誤碼范圍,是請求出錯才繼續(xù)重試爬取
print e.code
return download(url, retry - 1)
time.sleep(1) #等待1s,避免對服務(wù)器造成壓力,也避免被服務(wù)器屏蔽爬取
return html
下載指定頁面的內(nèi)容,并將其存入.txt
def crawled_page(crawled_url):
"""
爬取文章內(nèi)容
param crawled_url: 需要爬取的頁面地址集合
"""
html = download(crawled_url)
soup = BeautifulSoup(html, "html.parser")
title = soup.find('h1', {'class': 'title'}).text #獲取文章標(biāo)題
content = soup.find('div', {'class': 'show-content'}).text #獲取文章內(nèi)容
if os.path.exists('spider_res/') == False: #檢查保存文件的地址
os.mkdir('spider_res')
file_name = 'spider_res/' + title + '.txt' #設(shè)置要保存的文件名
file = open(file_name, 'wb') #寫文件
content = unicode(content).encode('utf-8', errors='ignore')
file.write(content)
file.close()
調(diào)用函數(shù)
url = "http://www.itdecent.cn/p/4a8749704ebf"
download(url)
crawled_page(url)
結(jié)果


參考: