我知道 html2text、BeautifulSoup 等实用程序,但问题是它们还提取 javascript 并将其添加到文本中,这使得很难将它们分开。
htmlDom = BeautifulSoup(webPage)
htmlDom.findAll(text=True)
或者,
from stripogram import html2text
extract = html2text(webPage)
这两个都提取了页面上的所有 javascript,这是不受欢迎的。
我只是想提取您可以从浏览器复制的可读文本。
最佳答案
如果你想避免使用 BeautifulSoup 提取 script
标签的任何内容,
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
),这样我就可以按顺序获取所有子项并进行我自己的过滤。
关于python - 使用 Python 从 HTML 中提取可读文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3172343/