python简单爬取笔趣网小说

2019-09-16  本文已影响0人  lucky_life
from lxml import etree
import requests
# header
headers = {
    'User-Agent':'Mozilla/5.0(Macintosh; Intel Mac OS X 10_11_4)\
    AppleWebKit/537.36(KHTML, like Gecko) Chrome/52 .0.2743. 116 Safari/537.36'
}
# 书籍链接
base_url = "http://www.biquku.la/8/8797/"
# 最开始的页面
next_page = "5353807.html"
# 小说存放位置
file = '/Users/zz/Documents/resin/8798.txt'
with open(file, 'w+') as f:
    while ".html" in next_page:
        url = base_url + next_page
        response = requests.get(url,headers = headers)
        response.encoding = 'utf8'
        html = response.text
        html_str = etree.HTML(html)
        # 从html找到下一章的链接
        next_page = html_str.xpath('.//div[@class="bottem2"]/a[contains(text(),"下一章")]/@href')
        print(next_page[0])
        next_page = next_page[0]
        # 取到章节的标题
        title = html_str.xpath('.//div[@class="bookname"]/h1/text()')
        # 写入章节标题,加入换行
        title = title[0]+'\n'
        f.writelines(title)
        print(title)
        # 取到章节内容
        content = html_str.xpath('.//div[@id="content"]/text()')
        for con in content:
            # 将取到的章节内容中的&nbsp替换为空格
            context = con.replace('\xa0',' ')
            print(context)
            context=context+'\n'
            f.writelines(context)
上一篇下一篇

猜你喜欢

热点阅读