美文网首页
python简单爬取笔趣网小说

python简单爬取笔趣网小说

作者: lucky_life | 来源:发表于2019-09-16 17:48 被阅读0次
    • 查看笔趣网的html结构
      • 取小说内容


        小说章节内容显示

        可以看到该网页是把小说内容放在一个ID为content的div里面的
        所以我们可以用.//div[@id='conten']/text()来取到内容

      • 取小说章节标题


        章节标题显示

        用google浏览器的检查可以看到章节标题的位置,可以用.//div[@class="bookname"]/h1/text()来取

      • 获取下一页链接


        上下章节显示

        通过查看,我们可以用.//div[@class="bottem2"]/a[contains(text(),"下一章")]/@href来取到下一章链接
        同时由于我现在是第一章,可以看到上一章显示并不是上一章节,并且没有带html结尾,所以我们可以猜测如果到了最后一个章节也会显示和第一章的上一章相同,所以我们可以判断下一页的链接是否有.html结尾

      • 最后的代码
    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)
    

    相关文章

      网友评论

          本文标题:python简单爬取笔趣网小说

          本文链接:https://www.haomeiwen.com/subject/ezilyctx.html