Python BeautifulSoup:AttributeError:&x27;NavigableString';对象没有属性';儿童';
当使用BeautifulSoup4时,我可以运行此代码以获得一个“Shout”,而不会出现问题。当我使用Python BeautifulSoup:AttributeError:&x27;NavigableString';对象没有属性';儿童';,python,beautifulsoup,Python,Beautifulsoup,当使用BeautifulSoup4时,我可以运行此代码以获得一个“Shout”,而不会出现问题。当我使用for循环时,我得到错误AttributeError:'navigablesting'对象没有属性'children' class Shout: def __init__(self, user, msg, date): self.user = user self.msg = msg self.date = date def getSho
for
循环时,我得到错误AttributeError:'navigablesting'对象没有属性'children'
class Shout:
def __init__(self, user, msg, date):
self.user = user
self.msg = msg
self.date = date
def getShouts():
#s is a requests Session()
new_shouts = s.get(shouts_url).text
#set shouts page as parsable object
soup = BeautifulSoup(new_shouts)
shouts = []
shout_heads = soup.find_all("h2", {'class': 'A'})
shout_feet = soup.find_all("h2", {'class': 'B'})
for i in range(len(shout_heads)):
shout = Shout('', '', '')
shout.user = list(list(list(shout_heads[i].children)[0].children)[1].children)[1].get_text()
foot = shout_feet[i].get_text().split('-')
shout.msg = foot[1]
foot[2] = foot[2].split()
shout.date = foot[2][0] + " " + foot[2][1]
shouts.append(shout)
return shouts
什么会导致此错误仅在循环过程中发生?
子项
不仅包括元素中的标记,还包括任何文本(使用navigablesting
对象建模)。即使是空白也会导致在第一个元素之前出现文本:
<h2>
<a href="...">Some text</a>
</h2>
比如说
注意,.children
为您提供了一个迭代器;如果您想要列表,*不要在.children
上使用list()
。改用.contents
属性,它是一个列表对象
最后但并非最不重要的一点是,当您可以直接在列表上循环时,不要在range()上使用循环:
for shout_head in shout_heads:
shout = Shout('', '', '')
shout.user = shout_head.find(True)[0] # etc.
如果需要合并两个列表,可以使用zip()
:
虽然您也可以使用find\u next\u sibling()
来查找那些额外的h2
元素,但如果这些元素交替使用的话。首先,非常感谢您帮助我摆脱所有这些list()
调用。我会看看我能做些什么来过滤掉文本节点,但是我确信每个“Shout”的格式都是一样的(没有额外的节点)。我现在知道我必须做更多的过滤,因为Shout\u feet[I]。get\u text()
返回的内容比我想要的要多。至于在range()
上循环,我想在一个循环中创建一个Shout()
。一个Shout()
从Shout\u头和Shout\u脚两个方面都取了,我不想直接在一个列表上循环。@kaloncpu57:对不起,我错过了。在这种情况下,可以使用zip()
。
for shout_head in shout_heads:
shout = Shout('', '', '')
shout.user = shout_head.find(True)[0] # etc.
for shout_head, shout_foot in zip(shout_heads, shout_feet):