You need to enable JavaScript to run this app. Python使用BeautifulSoup爬取OLX网站触发TypeError错误该如何解决
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.15 13:06:03