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)
谢谢! :)
如果您比较第一个版本和第二个版本,您会注意到:
First: soup.find("img",{"src":"../img/gifts/img1.jpg"}).parent.previous_sibling.get_text()
Second: soup.find("img","src=":"../img/gifts/img1.jpg"}).parent.previous_sibling.get_text()
第二个代码返回Attribute Error:'NoneType' object has no attribute 'parent'
因为它找不到src=="../img/gifts/img1.jpg"
在提供的汤中。
所以,如果你删除=
在第二个版本中,它应该可以工作。
顺便说一句,您应该明确要使用哪个解析器,否则bs4
将返回以下警告:
UserWarning:没有明确指定解析器,所以我使用最好的
该系统可用的 HTML 解析器(“lxml”)。这通常不是一个
问题,但是如果您在另一个系统或不同的系统上运行此代码
虚拟环境,它可能使用不同的解析器和行为
不同。
要消除此警告,请更改如下所示的代码:
BeautifulSoup([你的标记])
to this:
BeautifulSoup([您的标记], "lxml")
因此,正如警告消息中所述,您只需更改soup = BeautifulSoup(html.read())
to soup = BeautifulSoup(html.read(), 'lxml')
, 例如。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)