1

次のコマンドを実行すると、「AttributeError:'NoneType'オブジェクトに属性'string'」が表示されません。ただし、同じタスクがブロック文字列変数で実行される場合。できます。

私が間違っていることについて何か考えはありますか?

from BeautifulSoup import BeautifulSoup
from urllib        import urlopen

url = ("https://en.wikipedia.org/w/api.php?action=query&prop=extracts&titles=Albert%20Einstein&explaintext")

print ((BeautifulSoup(((urlopen(url)).read()))).find('extract').string).split("\n", 1)[0]
4

1 に答える 1

0
from BeautifulSoup import BeautifulSoup
from urllib import urlopen
url = ("https://en.wikipedia.org/w/api.php?action=query&prop=extracts&titles=Albert%20Einstein&explaintext")

soup = BeautifulSoup(urlopen(url).read())
print soup.find('extract')  # returns None

findメソッドは、タグ'extract'を持つものを検索していません。それが機能することを確認したい場合は、「pre」や「html」などのドキュメントに存在するHTMLタグを付けてください。

'extract'はxmlタグのように見えます。XMLの解析に関するBeautifulSoupのドキュメント( http://www.crummy.com/software/BeautifulSoup/bs3/documentation.html#Parsing XML )を読んでみてください。また、BeautifulSoupの新しいバージョンがあります(bs4)。APIの方がはるかに優れていると思います。

于 2012-05-16T12:21:51.147 に答える