【问题标题】:Extract text only except the content of script tag from html with BeautifulSoup使用 BeautifulSoup 从 html 中提取除 script 标签内容外的文本
【发布时间】:2019-05-11 01:57:04
【问题描述】:

我有这样的html

<span class="age">
    Ages 15
    <span class="loc" id="loc_loads1">
     </span>
     <script>
        getCurrentLocationVal("loc_loads1",29.45218856,59.38139268,1);
     </script>
</span>

我正在尝试使用BeautifulSoup 提取Age 15

于是我写了如下python代码

代码:

from bs4 import BeautifulSoup as bs
import urllib3

URL = 'html file'

http = urllib3.PoolManager()

page = http.request('GET', URL)

soup = bs(page.data, 'html.parser')
age = soup.find("span", {"class": "age"})

print(age.text)

输出:

Age 15 getCurrentLocationVal("loc_loads1",29.45218856,59.38139268,1);

我只想要Age 15 而不是script 标签内的函数。有没有办法只获取文本:Age 15?或者有什么方法可以排除script标签的内容?

PS:脚本标签太多,网址不同。我不喜欢 替换输出中的文本。

【问题讨论】:

    标签: python python-3.x beautifulsoup urllib3


    【解决方案1】:

    使用.find(text=True)

    前:

    from bs4 import BeautifulSoup
    
    html = """<span class="age">
        Ages 15
        <span class="loc" id="loc_loads1">
         </span>
         <script>
            getCurrentLocationVal("loc_loads1",29.45218856,59.38139268,1);
         </script>
    </span>"""
    
    soup = BeautifulSoup(html, "html.parser")
    print(soup.find("span", {"class": "age"}).find(text=True).strip())
    

    输出:

    Ages 15
    

    【讨论】:

      【解决方案2】:

      迟到的答案,但为了将来参考,您还可以使用decompose()html 中删除所有script 元素,即:

      soup = BeautifulSoup(html, "html.parser")                  
      # remove script and style elements                         
      for script in soup(["script", "style"]):                   
          script.decompose()                                     
      print(soup.find("span", {"class": "age"}).text.strip())    
      # Ages 15
      

      【讨论】:

      • 感谢您提供更多信息。我会记住这一点
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-31
      • 2014-11-29
      • 1970-01-01
      相关资源
      最近更新 更多