获取和转换HTML文档

2024-04-26 01:32:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我想创建一个脚本,下载一个网页,转换一些代码(从HTML到TeX),然后打印到一个文件。我拿到了前两部分,但我不知道怎么把它打印成文件。你知道吗

我使用正则表达式,但是我听说过很多关于它们的不好的地方,但是…我怎么能用那些HTML解析器来做到这一点呢?你知道吗

我获取一个url列表urllist,以及一个regex列表regexlist(第一项是搜索,第二项是替换)。我循环遍历所有url,并将每个url(通过regex转换后)保存到字典中的一个条目中。从那里开始,我想做的是将字典的每个条目打印到不同的文件中。你知道吗

顺便说一句,如果你想用另一种语言展示一个不同的解决方案来展示它的,那么毫无疑问,我正在寻找不同的语言:)而且,如果你用Python回答,你肯定可以通过使用一个好的解决方案来优化它。你知道吗

无论如何,这是我的密码。任何建议都会很好(我对这种语言和编程都是全新的)。你知道吗

import urllib
import re

outputpath = "~/Desktop/foo/"
webpath  = "http://learnyouahaskell.com/"
namelist = [ "introduction",
             "starting-out" ]
urllist = []
for i in range(len(namelist)):
  urllist.append(webpath + namelist[i])

regexlist = [ [ r"^<!DOCTYPE([\s\S]+?)<h1" , "\\startweb\n\n<h1" ],
              [ r"</p>[\s\n]*?<div class[\s\S]+?</script>\n</body>\n</html>", "</p>\n\n\\stopweb"],
              [ r"<h1.*?>(.+?)</h1>" , r"\chapter{\1}\n" ],
              [ r"<h2>(.+?)</h2>" , r"\section{\1}\n" ],
              [ r"<i>(.+?)</i>" , r"\emph{\1}" ],
              [ r"<em>(.+?)</em>" , r"\\bold{\1}" ],
              [ "<p>", "\n" ], [ "</p>", "\n" ],
              [ "<pre name=\"code\" class=\"haskell: (.+?)\">([\\s\\S]+?)\n?</pre>" , r"\n\starthaskell[\1]\2\n\stophaskell\n" ],
              [ "\n\n\\haskell" , "\n\haskell" ],
              [ "<span class=\"fixed\">(.+?)</span>" , r"\\typehaskell{\1}"],
              [ "<span class=\"label function\">(.+?)</span>" , r"\\haskellfunction{\1}"],
              [ "<span class=\"(class label|label class)\">(.+?)</span>" , r"\\haskellclass{\1}"],
              [ "<span class=\"label type\">(.+?)</span>" , r"\\haskelltype{\1}"],
              [ "<img src=\"(http://s3.amazonaws.com/lyah/)(.+?).png\" (alt|class)=\"(.+?)\" (class|alt)=\"(.+?)\" width=\"(\d+)\" height=\"(\d+)\">" , r"\n\placeimage[\2]{url=\1\2.png,\3=\4,\5=\6,width=\7pt,height=\8pt}\n" ],
              [ "<a href=\"(.+?)\">(.+?)</a>" , r"\\url[\1]{\2}" ],
              [ "<a.*?></a>", "" ],
              [ "#" , "\#" ],
              [ "&amp;" , "&" ],
              [ "&hellip;" , "\dots" ],
              [ "&gt;" , ">" ],
              [ "&lt;" , "<" ]
            ]

finaldoc = {}
for i in range(len(namelist)):
  htmlfile = urllib.urlopen(urllist[i])
  htmltext = htmlfile.read()
  for regex in regexlist:
    searchpattern  = regex[0]
    replacepattern = regex[1]
    htmltext = re.sub(searchpattern, replacepattern, htmltext)
  finaldoc[namelist[i]] = htmltext

Tags: 文件in语言urlforhaskellh1label