gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 01:04:48 24 4
gpt4 key购买 nike

我想使用漂亮的汤从标签中获取文本,我在我的计算机上尝试代码(运行 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 - 在不使用 str.text.strip() 的情况下通过 beautifulsoup 获取文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30947813/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com