gpt4 book ai didi

python - 属性错误 :'NoneType' 对象没有属性 'parent'

转载 作者:行者123 更新时间:2023-12-05 07:43:43 25 4
gpt4 key购买 nike

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' because it couldn't find src=="../img/gifts/img1.jpg " 在提供的汤中。

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


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

UserWarning: No parser was explicitly specified, so I'm using the best available HTML parser for this system ("lxml"). This usually isn't a problem, but if you run this code on another system, or in a different virtual environment, it may use a different parser and behave differently.

To get rid of this warning, change code that looks like this:

BeautifulSoup([your markup])

to this:

BeautifulSoup([your markup], "lxml")

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

关于python - 属性错误 :'NoneType' 对象没有属性 'parent',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43478806/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com