【问题标题】:Could not get visible text when using BeautifulSoup get_text or findAll(text=True)使用 BeautifulSoup get_text 或 findAll(text=True) 时无法获取可见文本
【发布时间】:2016-05-14 15:09:25
【问题描述】:

我正在尝试使用 bs4 和 python 3.4.1 从网页中提取可见文本。为此,我从汤中提取所有脚本和样式元素,然后继续从剩余的 html 中获取文本。

出于测试目的,我使用 x,y,z 来观察我的汤修改

html = urllib.request.urlopen('http://www.skilledup.com/articles/reasons-to-learn-python').read()
soup = BeautifulSoup(html, "html5lib") #tried xml and html.parser also
x = soup.prettify()
for elem in soup.find_all(['script', 'style']): #I know the text between <title></title> tags could not be interpreted as 'visible text' but thats's not the point of this example
    elem.extract()
y = soup.prettify()
z1 = soup.find_all(text=True)
z2 = soup.get_text()

我看到 x 是未更改的 HTML,y 是没有脚本和样式标签的相同 HTML,这是正确的。

z1 返回一个 ResultSet,它仍然包含一些 html 标签,例如 &lt;div class="category" id="article_top_name"&gt;&lt;/div&gt; AND 还有

/* * * CONFIGURATION VARIABLES * * */
var disqus_shortname = 'skilledupblog';
/* * * DON'T EDIT BELOW THIS LINE * * */
.... this continues with javascript

z2 是我想要完成的最简洁的版本,它为我提供了所有可见的文本,但在字符串的末尾仍然包含一个 javascript 的部分,比如这个:

/* * * CONFIGURATION VARIABLES * * */
var disqus_shortname = 'skilledupblog';
/* * * DON'T EDIT BELOW THIS LINE * * */
.... this continues with javascript

这不是一个孤立的案例,因为我在尝试使用的不同 html 页面上看到了类似的结果。

【问题讨论】:

    标签: python html beautifulsoup


    【解决方案1】:

    删除所有 scriptstyle 元素,然后获取 soup 的文本对我有用:

    import urllib.request
    
    from bs4 import BeautifulSoup
    
    html = urllib.request.urlopen('http://www.skilledup.com/articles/reasons-to-learn-python').read()
    soup = BeautifulSoup(html, "html5lib")
    
    for elem in soup.find_all(['script', 'style']):
        elem.extract()
    
    print(soup.get_text())
    

    在打印的文本中,没有disqus_shortname 或您提到的script 元素的任何其他部分。

    【讨论】:

      【解决方案2】:

      在使用初始配置(bs4 和 python 3.4.1)时,我仍然得到相同的结果,但是通过使用 Python 2.7.8 或 Python 35-32,我得到了清晰的预期 HTML,没有任何脚本和/或样式标签。不知道可能是什么原因,但这有效。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-01-23
        • 1970-01-01
        • 1970-01-01
        • 2010-12-28
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多