2017-04-18 52 views
2
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()) 

上記のコードはうまく動作しますが、下のコードは正常ではありません。上記のように属性エラーが発生します。誰か私に理由を教えてもらえますか?属性エラー: 'NoneType'オブジェクトに 'parent'属性がありません

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) 

ありがとうございます! :)

+0

両方とも収量$ 15.00 – Serge

+0

私は同じと言うことができます。私は再起動しようとしましたが、すべて同じエラーです。もう一度コードを調べてみます。ありがとう – Xexus

答えて

0

あなたが第一及び第二のバージョンを比較する場合は、あなたがそれに気付くでしょう:

まず: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="

第二のコードそれが提供スープにsrc=="../img/gifts/img1.jpg"を見つけることができなかったので、Attribute Error:'NoneType' object has no attribute 'parent'を返します。

したがって、2番目のバージョンで=を削除しても問題はありません。


ところで、あなたは、あなたが使用したいパーサ明示すべきそうbs4は、次の警告が返されます:警告メッセージで述べたように、あなただけにsoup = BeautifulSoup(html.read())を変更する必要があり、そう

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(), 'lxml')である。

+0

私はこのすべてに非常に新しいです。どうもありがとう!! – Xexus

関連する問題