Python报错TypeError: 'ResultSet'不可调用,爬取网页文本求助
Hey there! Let's sort out your two main issues: that annoying TypeError and extracting just the product names instead of full HTML tags.
1. Why the TypeError Happens
When you run bs_item.find_all('h2', class_="heading"), it returns a ResultSet—a list-like object that holds all matching <h2> tags. Your code tries to call this object like a function with list_item()—that's exactly what triggers the 'ResultSet' object is not callable error. You just need to iterate over the ResultSet directly, no parentheses needed.
2. Extracting Clean Text Content
Right now, printing each tag shows the full HTML because you're outputting the Tag object itself. To grab just the text inside the <h2> tags, use either the .text attribute or the .get_text() method (the latter is better for cleaning up extra whitespace or newlines).
Corrected Code
import requests from bs4 import BeautifulSoup res_item = requests.get('https://www.jetsetter.com/magazine/cool-tech-gadgets-on-amazon/') bs_item = BeautifulSoup(res_item.text, 'html.parser') list_item = bs_item.find_all('h2', class_="heading") # Iterate directly over the ResultSet (no parentheses!) for item_print in list_item: # Use .get_text() to extract and clean up the text print(item_print.get_text(strip=True))
Key Changes Explained
- Removed the unnecessary parentheses after
list_itemin the loop:for item_print in list_iteminstead oflist_item() - Added
item_print.get_text(strip=True)to pull out only the text content, withstrip=Truetrimming any messy extra spaces or line breaks around the product names
This should fix your error and give you exactly the clean product names you're looking for!
内容的提问来源于stack exchange,提问作者aliengamer90

