2016-12-16 57 views
0

无处不在,我仍然不知道它为什么会给出错误。这是一个YouTube教程,我的代码是相同的,所以我不知道为什么它会在下面提到的行中引发这个'NavigableString'错误(我在Python 2.7和3.5中都试过)。BeautifulSoup +请求>> AttributeError:'NavigableString'对象没有属性'find_all'

import requests 
from bs4 import BeautifulSoup 


url= "https://example.com" 
r = requests.get(url) 

soup = BeautifulSoup(r.content) 

data = soup.find_all("div", {"class": "example"}) 

for item in data: 
    print item.contents[0].find_all("a", {"class": "ex"}) # Error line 

编辑:其他有用的信息

教程:在教程http://youtube.com/watch?v=3xQTJi2tqgk

示例代码(时间:29:16):https://youtu.be/3xQTJi2tqgk?t=29m16s

网址教程:http://www.yellowpages.com/los-angeles-ca/coffe?g=los%20angles%2c%20ca&q=coffe

+0

'NavigableString'指内标签的纯文本从而可以没有subelementes,所以它不需要'find_all'。 – furas

+0

更好的问题添加链接到教程和网址,我们看到如果你的代码是真正相同的(如果它可以与当前页面 - 也许在页面上更改的东西)。 – furas

+0

https://www.youtube.com/watch?v=3xQTJi2tqgk – Keretto

回答

-1

A tag’s children are available in a list called .contents:

儿童包含标签和NavigableString,在你的情况下,.contents[0]是NavigableString它不要没有find_all方法

+0

所以我不应该使用'.contents [0]'? – Keretto

+0

发布html代码或网址 –

2

在你的“汤”你可能预期要得到的只是标签,这就是为什么你在呼唤.contents 。如果你对某个不是标签的内容调用.contents,那么它会抛出一个错误,这正在发生在你身上。

期待汤里的东西都是标签就是问题所在。并非汤中的所有东西都是标签,显然来自您的错误。可能会有评论,或空行或随机事件。当这些通过循环进入,你调用它们的内容时,它们没有对应的属性并抛出错误,因为它们根本不是标签,所以它们是NavigableStrings。

您应该首先将您的循环标记从NavigableStrings中分离出来。这样做: import NavigableString。然后在你的循环使用,如果else语句,或者说这种效果(尝试,但最后也将工作,如果语句语法适用于该条款)

if isinstance(object to test, NavigableString): 
    Do something in this situation 
else: 
    Things coming through here are tags, do something with this 
相关问题