python - 通过 beautifulsoup 获取文本而不使用 str.text.strip()

标签 python python-2.7 beautifulsoup

我想使用 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/

相关文章:

python - 保存 Excel 文件(openpyxl)然后尝试让 Excel 在 Mac 上打开它时出现 `Permission denied` 错误

python - 在字符串中搜索字符集

python - 在 Python Beautifulsoup 中使用 itertools 将数据项数据添加到分组中

python - 无法从 Selenium page_source 创建 soup?

python - 如何在 BeautifulSoup 中删除的标签周围添加空间

python - 如果在列文本字符串中找到值,如何使用字典键添加新的数据框列

python - 在python中使用正则表达式获取特定IP

python - Flask 中具有可变数量路径参数的正斜杠

python - 使用 Numpy 将值映射到更高维度

python - "import pkg.module"是否相当于 2.7 中 pkg/__init.py__ 中的 "import module"而不是 3.5 中的 0x104567910?