4

これは私のコードです:

from bs4 import BeautifulSoup as BS
import urllib2
url = "http://services.runescape.com/m=news/recruit-a-friend-for-free-membership-and-xp"
res = urllib2.urlopen(url)
soup = BS(res.read())
other_content = soup.find_all('div',{'class':'Content'})[0]
print other_content

しかし、エラーが発生します。

/Library/Python/2.7/site-packages/bs4/builder/_htmlparser.py:149: RuntimeWarning: Python's built-in HTMLParser cannot parse the given document. This is not a bug in Beautiful Soup. The best solution is to install an external parser (lxml or html5lib), and use Beautiful Soup with that parser. See http://www.crummy.com/software/BeautifulSoup/bs4/doc/#installing-a-parser for help.
  "Python's built-in HTMLParser cannot parse the given document. This is not a bug in Beautiful Soup. The best solution is to install an external parser (lxml or html5lib), and use Beautiful Soup with that parser. See http://www.crummy.com/software/BeautifulSoup/bs4/doc/#installing-a-parser for help."))
Traceback (most recent call last):
  File "web.py", line 5, in <module>
    soup = BS(res.read())
  File "/Library/Python/2.7/site-packages/bs4/__init__.py", line 172, in __init__
    self._feed()
  File "/Library/Python/2.7/site-packages/bs4/__init__.py", line 185, in _feed
    self.builder.feed(self.markup)
  File "/Library/Python/2.7/site-packages/bs4/builder/_htmlparser.py", line 150, in feed
    raise e

私は他の2人にこのコードを使用させましたが、それは彼らにとって完全にうまく機能します。なぜそれが私のために機能しないのですか?bs4をインストールしています...

4

1 に答える 1

6

エラーメッセージによると、あなたがする必要があるかもしれない1つのことはインストールですlxml。これはBeautifulSoupが使用するためのより強力な解析エンジンを提供します。概要については、ドキュメントのこのセクションを参照してください。ただし、他の2人で機能する理由としては、lxml(またはHTMLを適切に処理する別のパーサーが)インストールされていることが考えられます。つまり、BeautifulSoupは標準の組み込みの代わりにこのセクションを使用します。 (補足:あなたの例は、インストールされているシステムでも機能しlxmlますが、インストールされていないシステムでは失敗します)。

また、ドキュメントの次のメモを参照してください。

2.7.3より前のバージョンのPython2、または3.2.2より前のバージョンのPython 3を使用している場合は、lxmlまたはhtml5libをインストールすることが不可欠です。Pythonの組み込みHTMLパーサーは、古いバージョンではあまり良くありません。バージョン。

sudo apt-get install python-lxml実行して、問題が続くかどうかを確認することをお勧めします。

于 2012-12-20T05:19:03.973 に答える