You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用BeautifulSoup解析requests返回结果为XML时遇TypeError错误求助

Fixing "TypeError: object of type 'Response' has no len()" with BeautifulSoup and Requests

Ah, I’ve hit this exact snag before! The problem here is that you’re passing the full requests.Response object directly to BeautifulSoup, but BeautifulSoup needs the actual content of the response (the raw XML/HTML string), not the response wrapper itself.

Let’s break down why this error happens:

  • When you run requests.get(), it returns a Response object that holds metadata (like status codes, headers) plus the content.
  • BeautifulSoup tries to process the input as a string, but when it checks the length of the Response object, it throws that error because the object doesn’t have the __len__ method it expects.

Corrected Code

You need to pass either r.text (decoded string content) or r.content (raw bytes) to BeautifulSoup. Also, since you’re parsing XML, using html.parser isn’t ideal—switch to an XML-specific parser like lxml-xml for better results:

import requests
from bs4 import BeautifulSoup

r = requests.get(url, proxies=proxies, timeout=10)
# Use r.text for decoded string content, or r.content for raw bytes
result = BeautifulSoup(r.text, 'lxml-xml')
# If you don't have lxml installed, you can try the built-in 'xml' parser (though lxml is more reliable)
# result = BeautifulSoup(r.text, 'xml')

Note on XML Parsers

If you get an error about the parser not being available, install lxml first with this command:

pip install lxml

This should fix the TypeError and let you properly parse the XML from your request.

内容的提问来源于stack exchange,提问作者Kevin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:06:24