【问题标题】:BeatifulSoup get_text() function including css [duplicate]BeautifulSoup get_text() 函数,包括 css [重复]
【发布时间】:2016-02-22 22:47:00
【问题描述】:

使用这个 html:

<!DOCTYPE html
PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

<style type="text/css">
    body
    {
    font-size: 190%/1.2em;
    margin: 1.58em 16% 1.58em 16%;
    }
</style>
</head>
<body>

<p id="d0e119">De goede Martha zou bijna gedacht hebben veel te laat te zijn, want het middageten was nauwelijks aan de kook op het fornuis
in de keuken.</p>
<p id="d0e121">&#8220;Goed,&#8221; zeide ik bij mij zelven, &#8220;als hij honger heeft, zal mijn oom, die de ongeduldigste mensch is, luide jammerkreten aanheffen.&#8221;</p>

 <p>Sacr\xe9 bleu!</p>
</body>
</html>

并运行这个 python 脚本:

    from bs4 import BeautifulSoup
    import codecs



  with codecs.open('test2.htm', encoding='utf-8') as fileHandle, codecs.open('fname.txt', 'w',encoding='utf-8') as outfile: 
        soup = BeautifulSoup(fileHandle, "lxml")
        print (soup.get_text())
        outfile.write(soup.get_text())
        fileHandle.close()
        outfile.close()

我得到这个输出:

    body
    {
    font-size: 190%/1.2em;
    margin: 1.58em 16% 1.58em 16%;
    }



De goede Martha zou bijna gedacht hebben veel te laat te zijn, want het middageten was nauwelijks aan de kook op het fornuis
in de keuken.
“Goed,” zeide ik bij mij zelven, “als hij honger heeft, zal mijn oom, die de ongeduldigste mensch is, luide jammerkreten aanheffen.”
Sacr\xe9 bleu!

为什么提取的样式信息就像是文本一样?我认为 get_text 只是获取文本(=正文标签中的内容?)

【问题讨论】:

  • 如果可以使用lxml from lxml import html;tree = html.fromstring(_html) ;tree.xpath("//*[not(self::style) and not(self::script)]/text()")

标签: python html css beautifulsoup


【解决方案1】:

soup.get_text() 将收集页面上所有元素的文本。它不知道您不希望有style 元素的文本。一种常见的方法是从树中删除像stylescript 这样的元素,然后获取文本

tags_to_remove = ['script', 'style']
for tag in soup.find_all(tags_to_remove):
     tag.extract()

print(soup.get_text())

【讨论】:

  • 如果 get_text 采用关键字 arg 来忽略标签会很好
猜你喜欢
  • 2016-01-23
  • 2019-12-20
  • 1970-01-01
  • 2015-12-27
  • 2014-03-26
  • 2019-01-12
  • 2021-05-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多