Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
380 views
in Technique[技术] by (71.8m points)

CLI 应用,对于较复杂的用户定义逻辑,如何处理更优?

场景:爬取小说
完整代码:https://github.com/ForkFG/Ter...

fetch: async(page) => {
    page = page ?? args[1]
    if (!page) Err("fetch: Page can't be null.")

    const srcName = setting.sourceActive, src = setting.sources[srcName]
    const _html = await ajax(src.url.replace(/{page}/g, page))

    let _title = _html.match(/<title>(.*)</title>/)[1]
    if (_title.match(/^[3-5][01]d+/))
        Err(`fetch: HTTP error code: ${_title}`)
    _title = _title.replace(/ - 新笔趣阁.*/, "").replace("-", " @ ")
    const _content = _html.match(/<div id="content">(.*)</div>/)[1]
        .replace(/<br[ ][/]>/g, "
")
        .replace(/readx();/g, "")
        .replace(/&amp;/g, "&")
        .replace(/&nbsp;/g, " ")
    div("text", 1, 2)
    Log(_title, "
", _content)

    div("arround", 1, 2)
    const
        _arround = _html.match(/=keypage;([sS]*)function keypage/)[1],
        _prev = _arround.match(/prevpage="/(.*).html"/)?.[1],
        _next = _arround.match(/nextpage="/(.*).html"/)?.[1],
        arroundJSON =
`{
"prev": ${_prev ? '"' + _prev + '"' : "null"},
"curr": "${page}",
"next": ${_next ? '"' + _next + '"' : "null"},
"title": "${_title}"
}
`
    Log(arroundJSON)
    await writeConfig("arround", arroundJSON)

    div("EOF", 0, 1)
},

目前的配置文件

{
    "sourceActive": "xbqg",
    "sources": {
        "xbqg": {
            "url": "https://www.xsbiquge.com/{page}.html",
            "charset": "utf8"
        }
    }
}

问题在于各个网站中信息的位置不一样,目前用的是正则来获取。
本来想直接用户配置正则就好了,但是有时一个正则不够,每个网站可能还有点别的额外操作要整。

现在我有一些想法,但都不太满意:

  1. 整一套复杂的配置,用户需要为每个源编写数个正则,填充若干信息
  2. 用户拿 js 写一个回调,接收爬到的 html,返回需要的信息。这个函数所在文件路径应被写入配置。
  3. 同 2,但是把函数暴力 serialize,塞进配置,省得我到处加载。
  4. 同 3,但是闲得没事写个 DSL,用户配置起来方便(?)了许多。并且我懒得为这个 DSL 写文档。
  5. 用户直接修改 main.js,别配置了

希望大家提供一些思路,感谢!


PS 所谓用户,在该问题发布前仅指我一人
PPS 爬取小说仅为学习所需
PPPS 如问题沉底而无人回答,本人将甚感痛心;如能赏我星星一颗,则不胜感激


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神解答

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share

2.1m questions

2.1m answers

63 comments

56.7k users

...