Python使用BeautifulSoup爬取OLX网站触发TypeError错误该如何解决
报错修复说明
核心报错原因
requests.get()返回的是Response类型对象,而BeautifulSoup初始化要求传入字符串格式的网页源代码,直接传入Response对象就会触发object of type 'Response' has no len()的类型错误。
修复后的完整代码
from bs4 import BeautifulSoup import requests # 模拟浏览器请求头,规避反爬拦截 headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36" } # 发送请求,添加超时设置 resp = requests.get( url='https://www.olx.com.pk/mobile-phones_c1453/q-iphone-x', headers=headers, timeout=10 ) # 校验请求是否成功 resp.raise_for_status() # 传入resp.text即网页源码字符串到BeautifulSoup soup = BeautifulSoup(resp.text, 'lxml') # 改用稳定的属性定位商品,避免使用动态生成的随机类名 phone_items = soup.find_all('li', attrs={'data-testid': 'listing-grid-card'}) for item in phone_items: title = item.find('h6').text.strip() if item.find('h6') else '无商品标题' price = item.find('span', attrs={'data-testid': 'ad-price'}).text.strip() if item.find('span', attrs={'data-testid': 'ad-price'}) else '无报价' print(f"商品名称:{title} | 售价:{price}")
注意事项
- 运行前请确保已安装依赖:缺失lxml可执行
pip install lxml,缺失requests可执行pip install requests - 原有代码中循环内用全局soup查找的逻辑错误已修正,改为从当前遍历的商品节点中提取信息,避免重复返回第一个商品
- 平台前端类名多为动态生成的随机字符串,不要用这类类名做定位规则,优先使用固定的
data-testid等属性定位更稳定
内容的提问来源于stack exchange,提问作者Random_Guy
相关产品推荐
相关产品推荐

