首页 文章

在美丽的汤中找不到lxml

提问于
浏览
3

我正在尝试使用beautifulsoup4来解析一系列用XHTML编写的网页 . 我假设为了获得最佳结果,我应该与xml解析器配对,而且我所知道的唯一一个由beautifulsoup支持的是lxml .

但是,当我尝试按照beautifuloup文档运行以下内容时:

import requests

from bs4 import BeautifulSoup 
r = requests.get(‘hereiswhereiputmyurl’)
soup = BeautifulSoup(r.content, ‘xml’)

它会导致以下错误:

FeatureNotFound: Couldn't find a tree builder with the features you    
requested: xml. Do you need to install a parser library?

这让我疯狂 . 我发现了另外两个发布相同问题的用户的记录

这里How to re-install lxml?

在这里bs4.FeatureNotFound: Couldn't find a tree builder with the features you requested: lxml. Do you need to install a parser library?

我使用这篇文章(请参阅此行下方的链接)重新安装和更新lxml并更新了美丽的汤,但我仍然收到错误 . Installing lxml, libxml2, libxslt on Windows 8.1

Beautifulsoup正在运作,因为我运行了以下代码,它向我展示了它常用的标记语言汤= BeautifulSoup(r.content,'html.parser')

这是我的规格Windows 8.1 Python 3.5.2我在Anaconda 3中使用spyder ide来运行我的代码(诚然,我不太了解)

我确定这是一个初学者会做的混乱,因为正如我之前所说,我的编程经验非常少 .

我怎么能解决这个问题,或者如果它是一个已知的bug,你们会建议我只使用lxml自己来抓取数据 .

1 回答

  • 0

    我认为问题是 r.content . 通常它提供响应的原始内容,不一定是HTML页面,它可以是json等 .
    尝试喂汤 r.text .

    soup = BeautifulSoup(r.text, ‘lxml’)
    

    更好:

    r.encoding='utf-8'
    

    然后

    page = r.text
    
    soup = BeautifulSoup(page, 'lxml')
    

    如果要解析xml,可以使用 'lxml-xml' 作为解析器 .

相关问题