【问题标题】:Python, parsing the result from requests to xmlPython,将请求的结果解析为 xml
【发布时间】:2018-11-09 00:04:54
【问题描述】:

我正在尝试使用 BeautifulSoup 将请求的结果解析为 xml。

但是,它返回错误消息:“TypeError: object of type 'Response' has no len()”

这是我的代码:

r = requests.get(url, proxies=proxies, timeout=10)
result = BeautifulSoup(r,'html.parser')

【问题讨论】:

标签: python xml parsing beautifulsoup


【解决方案1】:

将响应内容传递给 BeautifulSoup。

例如:

result = BeautifulSoup(r.text,'html.parser')

【讨论】:

    【解决方案2】:

    根据previous answer 类似的问题:

    您将收到response.content。但它以字节 (docs) 的形式返回响应正文。但是您应该将 str 传递给 BeautifulSoup 构造函数 (docs)。所以你需要使用response.text 而不是获取内容。

    【讨论】:

      【解决方案3】:

      将 BeautifulSoup 函数中的 r 替换为 r.text:

      r = requests.get(url, proxies=proxies, timeout=10)
      
      result = BeautifulSoup(r.text,'html.parser')
      

      希望对您有所帮助。快乐编码:)

      【讨论】:

        【解决方案4】:

        在BeautifulSoup中,html.parser用于解析HTML内容,如果要解析XML内容,使用lxml的XML解析器,像这样:

        result = BeautifulSoup(r,'lxml-xml')   # method 1
        result = BeautifulSoup(r,'xml')        # method 2
        

        在你使用它们之前,你需要确保你已经安装了 lxml 解析器。使用 pip 安装很容易。

        pip 安装 lxml

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2015-05-30
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-03-18
          • 2019-03-07
          相关资源
          最近更新 更多