繁体   English   中英

属性错误:“ NoneType”对象没有属性“父级”

[英]Attribute Error:'NoneType' object has no attribute 'parent'

from urllib.request import urlopen
from bs4 import BeautifulSoup
html= urlopen("http://www.pythonscraping.com/pages/page3.html")
soup= BeautifulSoup(html.read())
print(soup.find("img",{"src":"../img/gifts/img1.jpg"
}).parent.previous_sibling.get_text())

上面的代码可以正常工作,但是下面的代码不能正常工作,它给出了如上所述的属性错误。 谁能告诉我原因?

from urllib.request import urlopen       
from bs4 import BeautifulSoup
html= urlopen("http://www.pythonscraping.com/pages/page3.html")
soup= BeautifulSoup(html.read())
price =soup.find("img",{"src=":"../img/gifts/img1.jpg"
}).parent.previous_sibling.get_text()
print(price)

谢谢! :)

如果比较第一版和第二版,您会注意到:

首先: soup.find("img",{"src":"../img/gifts/img1.jpg"}).parent.previous_sibling.get_text()

  • 注意: "src"

第二个: soup.find("img","src=":"../img/gifts/img1.jpg"}).parent.previous_sibling.get_text()

  • 注意: "src="

第二个代码返回Attribute Error:'NoneType' object has no attribute 'parent'因为在提供的汤中找不到src=="../img/gifts/img1.jpg"

因此,如果您在第二个版本中删除= ,它应该可以工作。


顺便说一句,您应该明确地使用哪个解析器,否则bs4将返回以下警告:

UserWarning:未明确指定解析器,因此我正在为此系统使用最佳的HTML解析器(“ lxml”)。 通常这不是问题,但是如果您在另一个系统或不同的虚拟环境中运行此代码,则它可能使用不同的解析器,并且行为不同。

要消除此警告,请更改如下代码:

BeautifulSoup([您的标记])

对此:

BeautifulSoup([您的标记],“ lxml”)

因此,如警告消息中所述,您只需要例如将soup = BeautifulSoup(html.read())更改为soup = BeautifulSoup(html.read(), 'lxml')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM