首页 文章

仅使用BeautifulSoup从html中提取除脚本标记内容之外的文本

提问于
浏览
3

我有像这样的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代码

code:

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)

output:

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

我只想 Age 15 不是 script 标签内的功能 . 有没有办法只获得文字: Age 15 ?或以任何方式排除 script 标签的内容?

PS:脚本标签太多,URL不同 . 我不喜欢从输出中替换文本 .

2 回答

  • 1

    迟到的答案,但为了将来参考,你也可以使用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
    
  • 1

    使用 .find(text=True)

    EX:

    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())
    

    Output:

    Ages 15
    

相关问题