Python爬虫运行报IndexError: list index out of range错误无法获取结果
问题原因
你遇到的IndexError: list index out of range报错,核心原因是container.findAll('div', {'class' : 'sc-bdVaJa Tile-iqbpf7-0 jRikHh'})没有匹配到任何元素,返回了空列表,后续直接调用[0]取第一个元素就触发了索引越界。
其他代码问题排查
- 你用来定位元素的class值
sc-bdVaJa Tile-iqbpf7-0 jRikHh是前端框架自动生成的动态class,网站每次更新都会变更,完全不能作为稳定的定位依据 - 前面获取商品容器的代码
page_soup.findAll("div", {"class" : ""}) [1:]逻辑错误,会匹配所有无class属性的div,根本捞不到正确的商品列表 - 连接关闭代码写错了,
uClient.close少了括号,应该是uClient.close(),否则请求连接不会正常释放
修复后代码
from urllib.request import Request, urlopen from bs4 import BeautifulSoup import ssl # 部分环境需要关闭ssl校验,无报错可删除 ssl._create_default_https_context = ssl._create_unverified_context my_url = 'https://www.officeworks.com.au/shop/officeworks/search?q=charger' # 加请求头模拟浏览器,避免被反爬拦截 req = Request(my_url, headers={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'}) # 发起请求 uClient = urlopen(req) page_html = uClient.read() uClient.close() # 解析页面 page_soup = BeautifulSoup(page_html, "html.parser") # 用稳定的data-testid属性定位商品容器,不会随前端更新变更 containers = page_soup.find_all("div", {"data-testid": "product-tile"}) if containers: # 取首个搜索结果 first_product = containers[0] # 用稳定属性定位商品标题 title_elem = first_product.find("a", {"data-testid": "product-tile-title"}) if title_elem: product_name = title_elem.text.strip() print(product_name) else: print("未匹配到商品标题") else: print("未匹配到任何商品列表")
开发建议
- 定位元素优先用
data-testid、id、固定语义的class,不要用动态生成的随机class - 每次调用
find/find_all后先判断返回结果是否为空,再读取属性或者取索引,避免触发异常 - 大多数电商网站有反爬策略,请求时建议携带浏览器UA、Cookie等信息,避免被拦截返回空页面
内容的提问来源于stack exchange,提问作者Cole Malcolm
相关产品推荐
相关产品推荐

