使用lxml,您可以尝试如下 *** 作:
import contextlibimport selenium.webdriver as webdriverimport lxml.html as LHimport lxml.html.clean as cleanurl="http://www.yahoo.com"ignore_tags=('script','noscript','style')with contextlib.closing(webdriver.Firefox()) as browser: browser.get(url) # Load page content=browser.page_source cleaner=clean.Cleaner() content=cleaner.clean_html(content) with open('/tmp/source.html','w') as f: f.write(content.enpre('utf-8')) doc=LH.fromstring(content) with open('/tmp/result.txt','w') as f: for elt in doc.iterdescendants(): if elt.tag in ignore_tags: continue text=elt.text or '' tail=elt.tail or '' words=' '.join((text,tail)).strip() if words: words=words.enpre('utf-8') f.write(words+'n')
除了图像中的文字和随时间变化的某些文字(使用javascript完成并刷新)之外,这似乎可以获取www.yahoo.com上几乎所有的文字。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)