【问题标题】:How to get all visible text in a web page (not html source)?如何获取网页中的所有可见文本(不是 html 源代码)?
【发布时间】:2020-01-11 10:57:28
【问题描述】:

例如,我想在“www.google.com”上显示文本,就像在 chrome 中打开它并按 ctrl+a & ctrl+c:

..   
Google PrivacyTermsSettingsAdvertisingBusinessAboutHow Search works

代替:

<!doctype html><html itemscope="" itemtype="http://schema.org/WebPage" lang="en"><head><meta charset="UTF-8"><meta content="origin" name="referrer"><meta content="Search the world's information, including webpages, images, videos and more. Google has many special features to help you find exactly what you're looking for." name="description"><meta content="noodp" name="robots"><meta content="/images/branding/googleg/1x/googleg_standard_color_128dp.png" itemprop="image"><meta content="origin" name="referrer"><title>Google</title><script nonce="kYKSVIWLPxNkDhoVCq276A==">(function(){window.google={kEI:'ZqUZXruXDNfT-
...

我已经尝试过 requests_html 模型,例如:

import requests_html
s = requests_html.HTMLSession()
page = s.get('https://www.google.com')
print(page.html.text)

但它仍然像打击一样显示html:

Google
(function(){window.google={kEI:'y6cZXu3LJ8SkwAPWz6KIBA',kEXPI:'31',authuser:0,kGL:'ZZ',kBL:'JGpW'};google.sn='webhp';google.kHL='en';google.jsfs='Ffpdje';})();(function(){google.lc=[];google.li=0;google.getEI=function(a){for(var b;a&&(!a.getAttribute||!(b=a.getAttribute("eid")));)a=a.parentNode;return b||google.kEI};google.getLEI=function(a){for(var b=null;a&&(!a.getAttribute||!(b=a.getAttribute("leid")));)a=a.parentNode;return b};
...

那么,我怎样才能在页面上显示所有文本,比如按 ctrl+a 和 ctrl+c?

谢谢。

【问题讨论】:

    标签: python python-3.x python-requests python-requests-html


    【解决方案1】:

    有几种方法可以做到这一点,但我通常使用的一种是:

    from bs4 import BeautifulSoup as bs
    import requests_html
    s = requests_html.HTMLSession()
    page = s.get('https://www.google.com')
    soup=bs(page.text,'lxml')
    print(soup.get_text())
    

    输出:

    关于商店 Gmail 图片登录 移除 报告不当联想 隐私条款设置搜索设置高级搜索您在搜索历史中的数据搜索帮助发送反馈广告业务搜索的工作原理

    【讨论】:

      猜你喜欢
      • 2021-12-03
      • 2021-02-17
      • 1970-01-01
      • 1970-01-01
      • 2020-10-31
      • 1970-01-01
      • 2011-12-18
      • 2011-02-07
      相关资源
      最近更新 更多