python - 属性错误: 'NavigableString' object has no attribute 'find_all' (NameError)

标签 python html beautifulsoup scrapy

import requests
from bs4 import BeautifulSoup
url=("http://finance.naver.com/news/mainnews.nhn")

r=requests.get(url)
soup=BeautifulSoup(r.content)

a_data = soup.find_all("li",{"class":"block1"})

for item in a_data:
    print item.contents[0].find_all("dt",{"class":"articleSubject"})[0].text

在这段代码中,当我运行这段代码时。我有这样的错误。 “AttributeError:‘NavigableString’对象没有属性‘find_all’”

我该如何解决这个问题??? 我已经尝试过 try and except 方法。然而,这并没有成功...

//html代码

<li class="block1">
<dl>
<dt class="articleSubject">
<span class="remark"></span> <!-- 말머리는 span class="remark" 로 묶임 -->
<a href="/news/news_read.nhn?       
article_id=0003289339&amp;office_id=009&amp;mode=mainnews&amp;type=&amp;date=2014-08-   
27&amp;page=1">**시총 9조 `모바일 공룡` 다음카카오 합병 승인…업계 지각변동 예고**</a>
</dt>
<dd class="articleSummary">
다음카카오가 합병을 위한 마지막 문턱을 넘어섰다. 네이버의 독주가 지속되고 있는 온라인·모바일 업계에    
적지 않은 시장 판도 변화가 예상된다.   27일 다음과 카카오는 각각 제주 ..
                                    <span class="press">매일경제 </span>
<span class="bar">|</span>
<span class="wdate">2014-08-27 11:40:05</span>
</dd>
</dl>
</li>

最佳答案

如果您尝试查找与带有 class 属性 articleSubjectdt 关联的文本,您可以直接在 项目

通过这样做:

>>> for item in a_data:
...     print item.find_all("dt",{"class":"articleSubject"})[0].text

打印:

**시총 9조 `모바일 공룡` 다음카카오 합병 승인…업계 지각변동 예고**

对于上面的 HTML。如果您针对代码中的 URL 运行此代码,您将获得 20 个结果。

item.contents 是一个以 \n 作为第一项的列表。因此,在新行字符上执行 find_all() 会引发 AttributeError

关于python - 属性错误: 'NavigableString' object has no attribute 'find_all' (NameError),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25562352/

相关文章:

html - 是否可以在电子邮件中使用渐变?

python - 如何将检索到的数据存储为 CSV 格式

python - 在 celery 任务中共享巨大的分类器对象

python - 输入错误: No module named 'tkinter'

javascript - 在 wordpress 中找不到 jQuery 函数

html - 改变 。在 html5 中输入类型 ='number' 上的(点)分隔符,(逗号)

python - Beautifulsoup 未到达子元素

html - 查找具有特定文本的 <td> 标签值(Beautiful Soup)

python - 如何从 Python 优雅地终止 GLib 主循环

python - psutil.cpu_times()返回的时间 "Unit "是多少?