python爬蟲其實並沒有什麼太高深的技術,耗費精力的地方在於對網站返回結果的解析,以及對一些反爬機制的研究。
爬蟲demo
下面這個例子可以爬取起點免費小說,直接看代碼(本例來源於參考資料1):
# coding=utf-8
import urllib2
import sys
from bs4 import BeautifulSoup
# 設置編碼
reload(sys)
sys.setdefaultencoding('utf-8')
startIndex = 0 # 默認第0本
startPage = 0 # 默認第0頁
# 獲取一個章節的內容
def getChapterContent(file, url):
try:
bookContentRes = urllib2.urlopen(url)
bookContentSoup = BeautifulSoup(bookContentRes.read(), "html.parser")
file.write(bookContentSoup.select("h3[class='j_chapterName'] span")[0].string + '\n')
for p in bookContentSoup.select(".j_readContent p"):
file.write(p.next + '\n')
except Exception, e:
# 如果出錯了,就重新運行一遍
print(e)
getChapterContent(file, url)
else:
chapterNext = bookContentSoup.select("a#j_chapterNext")[0]
if chapterNext.string != "書末頁":
nextUrl = "https:" + chapterNext["href"]
getChapterContent(file, nextUrl)
# 獲取當前頁所有書的內容
def getCurrentUrlBooks(url):
response = urllib2.urlopen(url)
the_page = response.read()
soup = BeautifulSoup(the_page, "html.parser")
bookArr = soup.select("ul[class='all-img-list cf'] > li")
global startIndex
if startIndex > 0:
bookArr = bookArr[startIndex:]
startIndex = 0
for book in bookArr:
bookCover = book.select("div[class='book-mid-info'] h4 > a")[0]
print "書名:" + bookCover.string
# 先創建.txt文件,然後獲取文本內容寫入
bookFile = open("/home/qingqianxiaoyi/crawler/books/" + bookCover.string + ".txt", "a+")
bRes = urllib2.urlopen("https:" + bookCover['href'])
bSoup = BeautifulSoup(bRes.read(), "html.parser")
bookContentHref = bSoup.select("a[class='red-btn J-getJumpUrl']")[0]["href"]
getChapterContent(bookFile, "https:" + bookContentHref)
bookFile.close()
nextPage = soup.select("a.lbf-pagination-next")[0]
return nextPage["href"]
if len(sys.argv) == 1:
pass
elif len(sys.argv) == 2:
startPage = int(sys.argv[1]) / 20 # 從第幾頁開始下載
startIndex = int(sys.argv[1]) % 20 # 從第幾本開始下載
elif len(sys.argv) > 2:
startPage = int(sys.argv[1])
startIndex = int(sys.argv[2])
# 根據傳入參數設置從哪裏開始下載
url = "//www.qidian.com/free/all?orderId=&vip=hidden&style=1&pageSize=20&siteid=1&pubflag=0&hiddenField=1&page=" + str(
startPage + 1)
# 死循環 直到沒有下一頁
while True:
if url.startswith("//"):
url = getCurrentUrlBooks("https:" + url)
else:
break
這裏主要用到了兩個庫,分別是urllib2和BeautifulSoup。urllib2是http請求庫,BeautifulSoup的官方解釋是:
-
Beautiful Soup提供一些簡單的、python式的函數用來處理導航、搜索、修改分析樹等功能。它是一個工具箱,通過解析文檔爲用戶提供需要抓取的數據,因爲簡單,所以不需要多少代碼就可以寫出一個完整的應用程序。
-
Beautiful Soup自動將輸入文檔轉換爲Unicode編碼,輸出文檔轉換爲utf-8編碼。你不需要考慮編碼方式,除非文檔沒有指定一個編碼方式,這時,Beautiful Soup就不能自動識別編碼方式了。然後,你僅僅需要說明一下原始編碼方式就可以了。
Beautiful Soup已成爲和lxml、html6lib一樣出色的python解釋器,爲用戶靈活地提供不同的解析策略或強勁的速度。