【问题标题】:how to print only text beautifulsoup如何只打印文本 beautifulsoup
【发布时间】:2017-06-19 21:54:07
【问题描述】:

我正在尝试了解 beautifulsoup 的工作原理以创建应用程序。

我可以使用 .find_all() 找到并打印所有元素,但是它们也可以打印 html 标签。如何只打印这些标签中的文本。

这就是我所拥有的:

from bs4 import BeautifulSoup

"""<html>
<p>1</p>
<p>2</p>
<p>3</p>
"""

soup = BeautifulSoup(open('index.html'), "html.parser")
i = soup.find_all('p')
print i

【问题讨论】:

标签: python python-2.7 beautifulsoup


【解决方案1】:

这可能会对您有所帮助:-

from bs4 import BeautifulSoup
source_code = """<html>
<p>1</p>
<p>2</p>
<p>3</p>
"""
soup = BeautifulSoup(source_code)
print soup.text

输出:-

1
2
3

【讨论】:

    【解决方案2】:
    soup = BeautifulSoup(open('index.html'), "html.parser")
    i = soup.find_all('p')
    for p in i:
        print p.text
    

    find_all() 将返回一个标签列表,你应该遍历它并使用tag.text 来获取标签下的文本

    更好的方法:

    for p in soup.find_all('p'):
        print p.text
    

    【讨论】:

      【解决方案3】:

      我认为你可以做他们在this stackoverflow question 所做的事情。使用findAll(text=True)。所以在你的代码中:

      from bs4 import BeautifulSoup
      
      """<html>
      <p>1</p>
      <p>2</p>
      <p>3</p>
      """
      
      soup = BeautifulSoup(open('index.html'), "html.parser")
      i = soup.findAll(text=True)
      print i
      

      【讨论】:

      • 这将返回HTML代码中的所有文本,包括注释,这绝对不是解决方案
      • 包括评论?你的意思是包括 cmets 吗?
      • Comment 对象只是NavigableString 的一种特殊类型
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-10-09
      • 1970-01-01
      • 2011-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多