1

次のように、情報が行のペアにグループ化されている(非常に不十分に定義された)htmlを処理したいと思います。

<html>
<body>
<table>
 <tr>
     <td>
         <font >
         <a href="a">ABC</a></font>
     </td>
 </tr>
 <tr>
     <td height="50">
         <font>When:</font><font>19-1-2013</font>
          <b><font>&nbsp; </font></b>
         <font>Where:</font><font>Here</font>
         <font>Who:</font><font>Me</font>
     </td>
 </tr>
 <tr>
     <td>
        <font >
             <a href="b">EFG</a>
        </font>
     </td>
 </tr>
 <tr>
     <td height="50">
         <font>When:</font><font>19-2-2013</font>
         <b><font>&nbsp; </font></b>
         <font>Where:</font><font>There</font>
         <font>Who:</font><font>You</font>
     </td>
 </tr>
 <tr>
     <td>
        <font >
            <a href="c">HIJ</a>
        </font>
     </td>
 </tr>
 <tr>
     <td height="50">
         <font>When:</font><font>19-3-2013</font><b>
         <font>&nbsp; </font></b>
         <font>Where:</font><font>Far away</font>
         <font>Who:</font><font>Him</font>
     </td>
 </tr>
</table>
</body>
</html>

これに対して、数回の反復の後、私はこのコードに到達して、私が望むものを達成しました。

import Data.List
import Control.Arrow.ArrowNavigatableTree
import Text.XML.HXT.Core
import Text.HandsomeSoup

group2 [] = []
group2 (x0:x1:xs) = [x0,x1]:(group2 xs)

countRows html = html >>> deep (hasName "tr") >. length

parsePage sz html = let
  n x = deep (hasName "tr") >. (( -> a !! x) . group2 ) >>> unlistA
  m = deep (hasName "td") >>> css "a" /> getText
  o = deep (hasName "td") >>> hasAttr "height" >>> (css "font" >. (take 1 . drop 4)) >>> unlistA /> getText
  p x = (((n x) >>> m) &&& ((n x) >>> o))
  in html >>> catA [p x | x <- [0..sz]]

main = do
    dt <- readFile "test.html"
    let html = parseHtml dt
    count <- (runX . countRows) html
    let cnt = ((head count) `div` 2) - 1
    prcssd <- (runX . (parsePage cnt)) html
    print prcssd

結果は次のようになります:[( "ABC"、 "Here")、( "EFG"、 "There")、( "HIJ"、 "Far away")]

ただし、これはあまり良いアプローチではないと思います。最初に行を数える必要があります。HXTを使用してこのグループ化を行うためのより良い方法はありますか?&&&演算子を少し運が良かったので試しました。

hxtを使用して複数のhtmlテーブルを抽出する際の質問は、便利ですが、より単純な状況を示していると思います。

4

2 に答える 2

3

数週間前にhxtでhtml解析を行ったところ、 xpathが非常に便利だと思いました。残念ながら、私はあなたの問題に対する完璧な解決策を思いつきませんでしたが、それは新しい試みの始まりかもしれません。

import Text.XML.HXT.Core
import Text.XML.HXT.XPath.Arrows

type XmlTreeValue a = a XmlTree String
type ParsedXmlTree a = a XmlTree XmlTree
type IOXmlTree = IOSArrow XmlTree XmlTree

-- parses a given .html file
parseHtml :: FilePath -> IOStateArrow s b XmlTree
parseHtml path = readDocument [withParseHTML yes, withWarnings no] path

-- "" for stdout
saveHtml :: IOXmlTree
saveHtml = writeDocument [withIndent yes] ""

extract :: IOXmlTree
extract = processChildren (process `when` isElem)

-- main processing functon
processHtml :: FilePath -> IO ()
processHtml src =
  runX (parseHtml src >>> extract >>> saveHtml)
   >> return ()

-- process the html structure
process :: ArrowXml cat => ParsedXmlTree cat
process =
  -- create tag <structure> for the expression given next
  selem "structure"
    -- navigate to <html><body><table><tr>...
    [(getXPathTrees "/html/body/table/tr")
      -- then combine the results
      >>> (getTheName <+> getWhere)]

 -- selects text at path <td><font><a...> </a></font></td> and creates <name>-Tag
 -- (// means that all <td>-tags are analysed,
 --  but I'm not quite sure why this is relevant here)
 getTheName :: ArrowXml cat => ParsedXmlTree cat
 getTheName = selem "name" [getXPathTrees "//td/font/a/text()"]

 -- selects text at path <td><font><a...> </a></font></td>
 -- (where the forth font-tag is taken) and creates <where>-Tag
 getWhere  :: ArrowXml cat => ParsedXmlTree cat
 getWhere = selem "where" [getXPathTrees "//td/font[4]/text()"]

結果は次のようになります。

*Main> processHtml "test.html"
<?xml version="1.0" encoding="UTF-8"?>
<structure>
 <name>ABC</name>
 <where/>
 <name/>
 <where>Here</where>
 <name>EFG</name>
 <where/>
 <name/>
 <where>There</where>
 <name>HIJ</name>
 <where/>
 <name/>
 <where>Far away</where>
</structure>

私が言ったように、完全ではありませんが、うまくいけばスタートです。

編集:多分これはあなたのアプローチのように見えます。それでも、気にしない要素を削除する代わりに、最初に、結果に適合するすべての要素を選択してフィルタリングします。そのような問題に対する一般的なアプローチがないことは非常に魅力的だと思います。なぜなら、どういうわけか、font [4]-selectionは他のアプローチでは機能しないからです-しかし、私はxpathの良いユーザーではないかもしれません。

processHtml :: FilePath -> IO [(String,String)]
processHtml src = do
  names <- runX (parseHtml src >>> process1)
  fontTags <- runX (parseHtml src >>> process2)
  let wheres = filterAfterWhere fontTags
  let result = zip names wheres
  return result
 where filterAfterWhere [] = []
       filterAfterWhere xs = case dropWhile (/= "Where:") xs of
                               []     -> []
                               [x]    -> [x]
                               _:y:ys -> y : filterAfterWhere ys

process1 :: ArrowXml cat => XmlTreeValue cat
process1 = textNodeToText getTheName

process2 :: ArrowXml cat => XmlTreeValue cat
process2 =  textNodeToText getWhere

getTheName :: ArrowXml cat => ParsedXmlTree cat
getTheName = getXPathTrees "//td/font/a/text()"

getWhere  :: ArrowXml cat => ParsedXmlTree cat
getWhere = getXPathTrees "//td/font/text()"

-- neet function to select a value within a XmlTree as String
textNodeToText :: ArrowXml cat => ParsedXmlTree cat -> XmlTreeValue cat
textNodeToText selector = selector `when` isElem >>> getText

このようにして、質問で示した結果が得られます。

*Main> processHtml "test.html"
[("ABC","Here"),("EFG","There"),("HIJ","Far away")]

Edit2:

おもしろい事実:hxt-xpathライブラリは、このようなインデックス選択には適切に機能しないようです。オンラインのXPath-evaluatorは、の正しい動作を示します//td/font[4]/text()

于 2013-02-19T18:58:28.583 に答える