试验python爬取逐浪小说

本文介绍了一位自学Python的作者尝试爬取逐浪小说的历程。通过BeautifulSoup解析网页,抓取小说的标题、章节及内容,并将其保存到本地文件。然而,代码中存在一些不规范之处,例如手动设置编码,且抓取到的文章内容没有自动换行。作者寻求解决方案,并分享了相关的逐浪小说爬取示例链接。
摘要由CSDN通过智能技术生成

只是想试下用python爬网页,之前用米花,后来米花不知道怎么回事打不开了,就用的逐浪。


#coding:utf-8

import sys
reload(sys)
sys.setdefaultencoding( "utf-8" )

import urllib,sys,urllib2,os
from bs4 import BeautifulSoup

IMAGE_DIR = '/home/cloud/temp/' #存放目录
if not os.path.exists(IMAGE_DIR):
    os.mkdir(IMAGE_DIR)


def get_book_without_db(url):
    """一边爬取一边写入,不用数据库保存"""
    soup = BeautifulSoup(request(url))
    title = (soup.find_all("title"))[0].string.split('_')[0] #文章名

    book_path = os.path.join(IMAGE_DIR, title)
    book = open(book_path, 'a+')
    i = 1
    for volume in soup.find_all('h2'):
        i += 1
        volume_name = volume.text
        print type(volume_name)
        book.write(str(volume_name) + '\n\n\n')
        for chapter in soup.find_all('ul')[i].find_all("li"):
            chapter_name = chapter.find('a').text
            book.write(str(chapter_name) + '\n')

            chapter_url = chapter.find('a').get('href')
            content_soup = BeautifulSoup(request(chapter_url))
            content = content_soup.find_all("p")[0].contents[0]
            book.write(str(content) + '\n\n')
    book.close()
    print '书籍路径: ', book_path


get_book_without_db('testurl')


其中,testurl是小说目录。

因为是自学的,代码中获取内容有些还是debug时看内存才写的,所以可能不规范。

另外,我爬取的文章内容是一段字符串,没有自动换行。百度没有查到,哪位知道的可否告知一下,文章内容该怎么自动换行?


注释:后来发现有个也是爬取逐浪的:http://www.oschina.net/code/snippet_1788589_48365

巧合啊,我是在优书网随便选的一个网站。不过此文好像也没有自动换行

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值