到处看,我仍然不知道它为什么会出错。这是一个YouTube教程,我的代码完全相同,所以我不知道为什么会抛出这个' NavigableString'下面提到的行上的错误(我在Python 2.7和3.5中都尝试过)。
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
教程中的url:http://www.yellowpages.com/los-angeles-ca/coffe?g=los%20angles%2c%20ca&q=coffe
答案 0 :(得分:2)
在你的'汤'中你可能期望只获得标签,这就是你打电话.contents的原因。如果你在不是标签的东西上调用了.contents,那么它会抛出一个错误,这就发生在你身上。
期望汤中的所有东西都是标签就是问题所在。汤中的所有东西都不是标签,显然不是你的错误。可能有评论,空白行或随机事物。当它们通过循环并且你在它们上面调用.contents时,它们没有对应的属性并抛出错误,因为它们根本不是标记,它们是NavigableStrings。
首先应将循环标记与NavigableStrings分开。做这个:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" action="add_location.php" name="add_location_form" id="add_location_form">
<div class="formitem">
<label for="street">Street Address:</label>
<input type="text" id="street" name="street" />
</div>
<div class="formitem">
<label for="city"> City:</label>
<input type="text" id="city" name="city" />
</div>
<div class="formitem">
<label for="zip">Zip:</label>
<input type="text" id="zip" name="zip" />
</div>
</form>
<div class="results"></div>
。然后在你的循环中使用这个if else语句,或者这个效果的东西(尝试,除非,如果语句在语法上适用于该子句,最后也会起作用)
import NavigableString
答案 1 :(得分:0)
您可以尝试类似
data=[]
for n in j.select('p')[1].contents:
data.append(n)
paras.append(data)
它将像这样在
内组合导航
[["The government doesn't know how many people have died of ",
<b>COVID</b>,
"-19, in part because it didn't require nursing homes to report cases to the CDC. In some states, over half of deaths are in nursing homes."],
['As most of the world early awaits a vaccine for ',
<b>COVID</b>,
'-19, a smaller group of people scoffs. They could spell real trouble in the effort to build widespread immunity.'],
答案 2 :(得分:-1)
标签的子项在名为.contents:
的列表中可用
children包含tag和NavigableString,在这种情况下,.contents[0]
是NavigableString,它没有find_all
方法