Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/symfony/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将lxml输出传递给BeautifulSoup_Python_Beautifulsoup_Lxml - Fatal编程技术网

Python 将lxml输出传递给BeautifulSoup

Python 将lxml输出传递给BeautifulSoup,python,beautifulsoup,lxml,Python,Beautifulsoup,Lxml,我的离线代码工作正常,但我无法通过lxml将网页从urllib传递到BeautifulSoup。我使用urllib进行基本身份验证,然后使用lxml进行解析(对于我们需要刮取的特定页面,它会给出一个很好的结果),然后再进行美化 #! /usr/bin/python import urllib.request import urllib.error from io import StringIO from bs4 import BeautifulSoup from lxml import e

我的离线代码工作正常,但我无法通过lxml将网页从urllib传递到BeautifulSoup。我使用urllib进行基本身份验证,然后使用lxml进行解析(对于我们需要刮取的特定页面,它会给出一个很好的结果),然后再进行美化

#! /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
我不知道如何处理操作错误,所以我寻求另一种方法。我发现了使用lxml.html而不是lxml.etree的建议,因此下一次尝试是:

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
尝试3
page=urllib.request.urlopen(请求)
doc=page.read()
#打印(文档)
html=html.document\u fromstring(doc)
打印(html)
# 
soup=BeautifulSoup(html)#也尝试过(html,“lxml”)
#TypeError:应为字符串或缓冲区
这显然给出了某种结构,但如何将其传递给BeautifulSoup?我的问题有两个:如何将页面从urllib传递到lxml.etree(如附件1所示,最接近我的工作代码)?或者,如何将lxml.html结构传递给BeautifulSoup(如上所述)?我知道两者都围绕着数据类型,但不知道该怎么处理它们

python 3.3、lxml 3.0.1、Beautifulsoup4。我是python新手。感谢互联网提供的代码片段和示例。

BeautifulSoup可以使用,无需使用这些长度

BeautifulSoup(doc, 'lxml')

天哪,谢谢你!我看到了那一页,但不明白它有那么简单。再次感谢。