python簡單爬蟲-幫媳婦爬取小說

媳婦說想看 《公子九》,先百度找了一個可以爬取的網站。
第一,這個網站不需要賬號登錄;第二,不會因為平凡訪問封IP;這種網頁爬取就簡單了,只需要獲取網頁,解析網頁得到內容,存入文件txt。

http://www.mpzw.com/html/129/129853/
上面是一個目錄頁面,可以以這個頁面作為入口,依次爬取各章節。

查看其源代碼:.png

查看源代碼,每個章節都有一個鏈接,其實第五章的地址就是:www.mpzw.com/html/129/129853/ 加上 27468861.html

腳本代碼如下

定義一個函數get_text()來獲取章節內容(使用BeautifulSoup包來解析),然后遍歷每個章節。最后下載的小說在存入out.txt 文件。當然還可以把每個爬取過的鏈接存下來方便下次爬取的時候跳過。

# -*- coding: utf-8 -*-
"""
Created on Sun Oct 22 15:11:15 2017

@author: Administrator
"""

from BeautifulSoup import BeautifulSoup
import urllib2

def get_text(url,title):
    '''
    解析小說的某一章節,輸出到文件
    url = 'http://www.mpzw.com/html/129/129853/27468857.html'
    title='第一章'
    '''
    out=open('out.txt','a+')  #追加模式
    out.write('\n\n'+title)
    f = urllib2.urlopen(url)
    soup = BeautifulSoup(f.read()) #.prettify('gbk')
    print soup.title.prettify('gbk')    #標題
    str1= soup.findAll('div',attrs ={'class':'Content'})[0].prettify('gbk') #正文
    str1=str1.replace(' ','')
    str1=str1.replace('<br />','\n')
    str1=str1.replace(' ','')
    str1=str1.replace('\n\n\n','\n')
    str1=str1.replace('\n\n','\n')
    str1=str1.replace('貓撲中文www.mpzw.com','')
    for i in str1.split('\n'):
        if '<' not in i :
            out.write(i+'\n')
    out.close()
#下一張
#get_text('http://www.mpzw.com/html/129/129853/27468857.html','a')

#入口網址
muluurl='http://www.mpzw.com/html/129/129853/'
f = urllib2.urlopen(muluurl+'index.html')
soup = BeautifulSoup(f.read())      #解析網頁
links=soup.findAll('a')             #所有的章節鏈接

for link in links:  #遍歷所有的章節
    try:
       title=link.text
       print title
       url=muluurl+link['href']
       print url
       get_text(url,title)
    except:
       print '鏈接錯誤,跳過'

希望以后能寫出更復雜的爬蟲。。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容