我想使用 beautiful soup 从标签中获取文本,我在我的计算机上尝试了代码(运行 mac OSX Yosemite)并且它工作正常,但是当我在 Linux 服务器上运行此代码(运行 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_
属性正确匹配,因为有两个类分配给 div
。
要使 BeautifulSoup 与多个类匹配,您需要使用 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()
关于python - 通过 beautifulsoup 获取文本而不使用 str.text.strip(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30947813/