1

我正在解析 robots.txt 文件,并且我已经编写了解析器以成功解析“格式正确”的 robots.txt 文件。我已经能够调整解析器以跳过以符号开头的行(例如 # 或 / 用于注释),但仅使用inClass "#/".

我无法解决的一个问题是如果一行不包含我想要匹配的字符串,则跳过它。

User-agent: *
Disallow: /includes/
Disallow: /misc/
Disallow: /modules/
Doesn't belong here
Disallow: /profiles/
Disallow: /scripts/
Disallow: /themes/

我首先尝试使用匹配:

satisfy (notInClass "DdUu") *> skipWhile (not . isEndOfLine)

并且认为这样做会否定我对特定注释行解析器的需求,因为哈希或斜杠不属于字符类。问题是这行不通。

我也意识到它无论如何都不会起作用,因为它不会解决诸如“不允许”与“不允许”之类的匹配问题。

这是解析代码(没有注释跳过代码,这仅适用于格式良好的 robots.txt):

{-# LANGUAGE OverloadedStrings, RankNTypes #-}

import           Prelude hiding (takeWhile)
import           Control.Applicative hiding (many)
import           Data.Char
import           Data.Text as T hiding (toLower)
import           Data.Text.Encoding as E
import           Control.Monad
import           Data.Attoparsec.ByteString
import qualified Data.Attoparsec.Char8 as AC
import           Data.Array.Unboxed
import           Data.ByteString as B hiding (takeWhile)
import qualified Data.ByteString.Internal as BI
import           Data.Word (Word8)

type RuleMap = [(ByteString, ByteString)]

-- newtype for indexable ua
newtype UserAgent = UserAgent { unUA :: ByteString }
    deriving (Eq, Ord, Show)

data RuleSet = RuleSet
    { userAgent :: UserAgent,
      rules     :: RuleMap }
     deriving (Eq, Ord, Show)

main = do
    r <- B.readFile "/Users/ixmatus/Desktop/robots.txt"
    print $ parse (many1 parseUABlock) r

stripper = E.encodeUtf8 . T.strip . E.decodeUtf8

isNotEnd = not . AC.isEndOfLine

-- | Catch all character matching, basically
matchALL :: Word8 -> Bool
matchALL = inClass ":/?#[]@!$&'()*%+,;=.~a-zA-Z0-9 _-"

-- | @doParse@ Run the parser, complete the partial if the end of the stream has
-- a newline with an empty string
doParse :: ByteString -> [RuleSet]
doParse cont =
    case parse (many1 parseUABlock) cont of
        Done _ set -> set
        Partial f -> handlePartial (f B.empty)
        Fail {} -> []

-- | @handlePartial@ Handle a partial with empty string by simply
-- returning the last completion
handlePartial :: forall t a. IResult t [a] -> [a]
handlePartial (Done _ r) = r
handlePartial (Fail {})  = []

-- | @parseUABlock@ Parse a user-agent and rules block
parseUABlock = do
    ua    <- parseUACol *> uA
    rulez <- many1 parseRules

    return RuleSet { userAgent = UserAgent ua,
                     rules = rulez }

-- | @matchUACol@ Parse the UA column and value taking into account
-- possible whitespace craziness
parseUACol = AC.skipSpace
          *> AC.stringCI "User-Agent"
          <* AC.skipSpace
          *> AC.char8 ':'
          *> AC.skipSpace

uA = do
    u <- takeWhile1 isNotEnd
    return (stripper u)

-- | @parseRules@ Parse the directives row
parseRules = (,) <$> parseTransLower
             <*> directiveRule

directiveRule = do
    rule <- takeWhile1 matchALL <* many1 AC.endOfLine

    return (stripper rule)

parseTransLower = do
    res <- parseDirectives <* AC.skipSpace
    return (lowercase res)

ctypeLower = listArray (0,255) (Prelude.map (BI.c2w . toLower) ['\0'..'\255']) :: UArray Word8 Word8
lowercase = B.map (\x -> ctypeLower!x)

directives = AC.stringCI "Disallow" <|> AC.stringCI "Allow"

-- | @parseDirectives@ Parse the directive column and any possibly
-- funny whitespace
parseDirectives = AC.skipSpace
                  *> directives -- <|> AC.stringCI "Crawl-delay" <|> AC.stringCI "Sitemap")
                  <* AC.skipSpace
                  <* AC.char8 ':'
4

1 回答 1

1

考虑这种方法。

定义:

data RobotsDirective = RobotsDirective String String

这表示 robots.txt 文件中的已解析指令。第一个字符串是指令(即UserAgent, Allow,Disallow等),第二个字符串是冒号后面的内容。

现在为 a 编写一个解析器RobotsDirective

parseRD :: Parser RobotsDirective

parseRD将查找指令名称(应仅包含字母、数字和破折号,可能还有下划线),后跟一个冒号,后跟零个或多个非换行符。适当地忽略空白。如果parseRD找到这样的模式,它将创建并返回一个RobotsDirective. 否则它将跳过一行字符并重试。

现在您有了 a 的解析器,您可以以标准方式RobotsDirective创建解析器。[RobotsDirective]

这个解析器只是跳过任何看起来不像指令的行,这将包括空行、注释行和以 . 开头的行Don't allow...。但是,它可以返回一个RobotsDirective在 robots.txt 文件中无效的行,即:

foo: blah

将返回RobotsDirective "foo" "blah"。解析 robots.txt 文件并获得RobotsDirective值列表后,只需浏览该列表并忽略您不感兴趣的值。

于 2013-04-10T05:08:53.063 回答