1

オフラインコードは正常に機能しますが、urllibからlxmlを介してBeautifulSoupにWebページを渡すのに問題があります。基本認証にurllibを使用し、次にlxmlを使用して解析し(スクレイプする必要のある特定のページで良好な結果が得られます)、BeautifulSoupに使用します。

#! /usr/bin/python
import urllib.request 
import urllib.error 
from io import StringIO
from bs4 import BeautifulSoup 
from lxml import etree 
from lxml import html 

file = open("sample.html")
doc = file.read()
parser = etree.HTMLParser()
html = etree.parse(StringIO(doc), parser)
result = etree.tostring(html.getroot(), pretty_print=True, method="html")
soup = BeautifulSoup(result)
# working perfectly

それが機能しているので、urllibを介してページをフィードしようとしました:

# attempt 1
page = urllib.request.urlopen(req)
doc = page.read()
# print (doc)
parser = etree.HTMLParser()
html = etree.parse(StringIO(doc), parser)
# TypeError: initial_value must be str or None, not bytes

エラーメッセージを処理しようとして、私は試しました:

# attempt 2
html = etree.parse(bytes.decode(doc), parser)
#OSError: Error reading file

OSErrorをどうしたらいいかわからなかったので、別の方法を探しました。lxml.etreeの代わりにlxml.htmlを使用する提案を見つけたので、次の試みは次のとおりです。

attempt 3
page = urllib.request.urlopen(req)
doc = page.read()
# print (doc)
html = html.document_fromstring(doc)
print (html)
# <Element html at 0x140c7e0>
soup = BeautifulSoup(html) # also tried (html, "lxml")
# TypeError: expected string or buffer

これは明らかにある種の構造を与えますが、それをBeautifulSoupに渡す方法は?私の質問は2つあります:urllibからlxml.etreeにページを渡すにはどうすればよいですか(attampt 1のように、作業コードに最も近い)?または、(上記のように)lxml.html構造をBeautifulSoupに渡すにはどうすればよいですか?どちらもデータ型を中心に展開していることは理解していますが、どうしたらよいかわかりません。

python 3.3、lxml 3.0.1、BeautifulSoup4.pythonは初めてです。コードの断片と例を提供してくれたインターネットに感謝します。

4

1 に答える 1

3

BeautifulSoupはlxmlパーサーを直接使用でき、これらの長さにする必要はありません。

BeautifulSoup(doc, 'lxml')
于 2012-12-11T23:34:32.007 に答える