4

我知道 html2text、BeautifulSoup 等实用程序,但问题是它们还提取 javascript 并将其添加到文本中,从而难以将它们分开。

htmlDom = BeautifulSoup(webPage)

htmlDom.findAll(text=True)

交替,

from stripogram import html2text
extract = html2text(webPage)

这两个都提取页面上的所有 javascript,这是不希望的。

我只是想提取可以从浏览器中复制的可读文本。

4

4 回答 4

6

如果您想避免script使用 BeautifulSoup 提取标签的任何内容,

nonscripttags = htmlDom.findAll(lambda t: t.name != 'script', recursive=False)

将为您执行此操作,获取作为非脚本标签的根的直接子代(并且单独的htmlDom.findAll(recursive=False, text=True)将获取作为根的直接子代的字符串)。您需要递归地执行此操作;例如,作为生成器:

def nonScript(tag):
    return tag.name != 'script'

def getStrings(root):
   for s in root.childGenerator():
     if hasattr(s, 'name'):    # then it's a tag
       if s.name == 'script':  # skip it!
         continue
       for x in getStrings(s): yield x
     else:                     # it's a string!
       yield s

我正在使用childGenerator(代替findAll),以便我可以让所有孩子按顺序排列并进行自己的过滤。

于 2010-07-03T18:39:25.603 回答
0

使用 BeautifulSoup,大致如下:

def _extract_text(t):
    if not t:
        return ""
    if isinstance(t, (unicode, str)):
        return " ".join(filter(None, t.replace("\n", " ").split(" ")))
    if t.name.lower() == "br": return "\n"
    if t.name.lower() == "script": return "\n"
    return "".join(extract_text(c) for c in t)
def extract_text(t):
    return '\n'.join(x.strip() for x in _extract_text(t).split('\n'))
print extract_text(htmlDom)
于 2010-07-03T18:32:10.000 回答
0

您可以删除美丽汤中的脚本标签,例如:

for script in soup("script"):
    script.extract()

移除元素

于 2010-07-03T18:35:37.180 回答