小说下载,SAX and DOM

请看代码:

复制代码
from html.parser import HTMLParser # pip install html-parser
from htmldom import htmldom # pip install htmldom
import urllib.request
import time

H = 'http://www.somewhere.com'
f = open('downloaded-novel.html', 'w', encoding='utf-8', newline='\n')
f.write('<html><style>*{font:10pt serif}</style>\n')

class Index_Parser(HTMLParser):
    def __init__(m, html):
        super().__init__(); m.href = None; m.feed(html);
    def handle_starttag(m, tag, attrs):
        if tag != 'a': return
        for name,link in attrs:
            if name != 'href': continue
            if not link.startswith('/novel/chapter_'): continue
            m.href = link; return
    def handle_data(m, data):
        if not m.href: return
        f.write('<h6>' + data + '</h6>\n')
        url = H + m.href; print(url)
        dom = htmldom.HtmlDom(url).createDom()
        for p in dom.find('p'):
            h = p.html()
            if h.find('href') == -1: f.writelines((h, '\n'))
        f.write('\n'); time.sleep(1) # be nice
        dom = m.href = None

Index_Parser(urllib.request.urlopen(H + '/novel/429').read().decode())
复制代码
posted @   Fun_with_Words  阅读(70)  评论(0编辑  收藏  举报
(评论功能已被禁用)
编辑推荐:
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?









 和4张牌。

点击右上角即可分享
微信分享提示