Skip to main content
 首页 » 编程设计

python之BS4 + Python3 : unable to crawl tree: 'NavigableString' object has no attribute 'has_attr'

2024年11月01日9emanlee


我是 Python 的新手(我只知道 powershell),我正在尝试使用 BS4+Python3 学习网络爬虫。

这是我练习的一个简单练习:

<h1 class="entry-title"> 
<a href="test1.html">test1</a></h1> 
<h1 class="entry-title"> 
<a href="test2.html" rel="bookmark">test2</a></h1> 

我想做的是仅获取具有属性“rel”的详细信息(href 和 .string)

这是我的代码

for h1_Tag in soup.find_all(("h1", { "class" : "entry-title" })): 
    for a_Tag in h1_Tag.contents: 
        if a_Tag.has_attr('rel'): 
           print (a_Tag) 

但我得到: AttributeError: 'NavigableString' 对象没有属性 'has_attr'

我做错了什么? 感谢您的帮助。

谢谢!

请您参考如下方法:

您正在遍历所有内容,包括 NavigableString对象;例如文本。

如果你想找到所有带有 rel 的元素属性,而是搜索它们:

for h1_Tag in soup.find_all(("h1", { "class" : "entry-title" })): 
    for a_Tag in h1_Tag.find_all('a', rel=True): 
       print(a_Tag) 

rel=True关键字参数将搜索限制为具有该属性的元素; <a>没有 rel 的标签属性将被跳过。