在不使用 str.text.strip() 的情况下通过 beautifulsoup 获取文本

get text by beautifulsoup without using str.text.strip()

我想使用漂亮的汤从标签中获取文本,我在我的计算机上尝试了代码(运行ning mac OSX Yosemite) 并且它有效正确但是当我在 Linux 服务器上 运行 这段代码时(运行ning Ubuntu 10.4)我得到这个错误:

mtemp = div_tag.text.strip()

AttributeError: 'NoneType' object has no attribute 'text'

代码就是:

    div_tag = soup.find('div', class_='span12 path_item')

    mtemp = div_tag.text.strip()
    print mtemp

我需要从该标签中获取文本,但我不知道为什么服务器上没有 运行 代码,我必须找到一种方法从标签中获取纯文本使用 div_tag.text.strip() 如果有帮助,您可以在此处查看 div_tag 内容(文本/我想从 html 代码中获取的内容)和 div_tag 它自己:

应邀 م带 刚开始 میراث فرهنگی ??????
<div class="span12 path_item">
        <a href="/" style="margin-right: 5px;"><i class="fa fa-arrow-left"></i> صفحه اصلی</a>
        
        <a href="/list/show-places" id="PlaceHolderDivMainContent_MainContent_MainContent_hamgardiSiteView_NavigationBar_ASites" style="cursor:pointer"><i class="fa fa-angle-left"></i>مکان‌ها</a>
        
        <a href="/list/show-places/Category-Tourism" id="PlaceHolderDivMainContent_MainContent_MainContent_hamgardiSiteView_NavigationBar_ACategory" style="cursor:pointer"><i class="fa fa-angle-left"></i>گردشگری</a>
        <a href="/list/show-places/Category-Tourism/SubCategory-59" id="PlaceHolderDivMainContent_MainContent_MainContent_hamgardiSiteView_NavigationBar_ASubCategory" style="cursor:pointer"><i class="fa fa-angle-left"></i>میراث فرهنگی</a>
        <a id="PlaceHolderDivMainContent_MainContent_MainContent_hamgardiSiteView_NavigationBar_Title"><i class="fa fa-angle-left"></i>کاخ موزه گلستان</a>
        
    </div>

首先,您的选择器将无法与您指定的 class_ 属性正确匹配,因为有两个 class 分配给了 div

要使 BeautifulSoup 匹配多个 class,您需要使用 CSS 选择器。

这段代码可以,但我不是很喜欢,如果有什么想法我会改进它:

from bs4 import BeautifulSoup as bs
#s  = your html
soup = bs(s)
d = soup.select('div.span12.path_item')
e = bs( str(d[0]) )
for x in e.find_all('a'):
    print x.text.strip()