dem*_*mos 4 html python text-extraction
我知道像html2text,BeautifulSoup等的utils,但问题是他们也提取javascript并将其添加到文本中,因此很难将它们分开.
htmlDom = BeautifulSoup(webPage)
htmlDom.findAll(text=True)
Run Code Online (Sandbox Code Playgroud)
交替,
from stripogram import html2text
extract = html2text(webPage)
Run Code Online (Sandbox Code Playgroud)
这两个都提取了页面上的所有javascript,这是不受欢迎的.
我只是想要提取您可以从浏览器中复制的可读文本.
如果您想避免script使用BeautifulSoup 提取任何标签内容,
nonscripttags = htmlDom.findAll(lambda t: t.name != 'script', recursive=False)
Run Code Online (Sandbox Code Playgroud)
将为您做到这一点,让root的直接子项是非脚本标记(并且单独的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
Run Code Online (Sandbox Code Playgroud)
我正在使用childGenerator(代替findAll),以便我可以让所有的孩子按顺序进行自己的过滤.