使用BeautifulSoup解析requests返回结果为XML时遇TypeError错误求助
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 aResponseobject 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
Responseobject, 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

