【问题标题】:How to filter HTML nodes which have text in it from a html page如何从 html 页面中过滤包含文本的 HTML 节点
【发布时间】:2018-09-06 12:27:21
【问题描述】:

我是网络抓取的新手,遇到了一个问题

我正在使用 BeautifulSoup 来抓取网页。我想获取其中包含文本的节点。

我尝试过像这样使用 get_text() 方法

  soup = BeautifulSoup(open('FAQ3.html'), "html.parser")                               
  body = soup.find('body')                                                                                                                  
  for i in body:                                                                       
    if type(i) != bs4.element.Comment and type(i)!= bs4.element.NavigableString :     
      if i.get_text():                                                             
        print(i)                                                                   

但是 get_text 正在给节点,即使它的子节点中有文本,

示例 html:

<div>
  <div id="header">
        <script src="./FAQ3_files/header-home.js"></script>
  </div>
  <div>
   <div>
      this node contain text
    </div>
 </div>
</div>

在检查最上面的 div 本身时,它返回整个节点,因为最里面有文本,

如何遍历所有节点并仅过滤其中实际包含文本的节点?

【问题讨论】:

    标签: python-3.x web-scraping beautifulsoup


    【解决方案1】:

    我为此使用了深度优先搜索,它解决了我的用例

    def get_text_bs4(self, soup, leaf):
            if soup.name is not None:
                if soup.string != None and soup.name != 'script': 
                        if soup.text not in leaf:
                            leaf[soup.text] = soup
                for child in soup.children:
                    self.get_text_bs4(child, leaf)
            return leaf
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-06-06
      • 1970-01-01
      • 1970-01-01
      • 2023-03-02
      • 1970-01-01
      • 1970-01-01
      • 2017-01-07
      • 2020-09-17
      相关资源
      最近更新 更多