You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Python爬取telguarder.com时CSS选择器触发索引越界错误求助

解决CSS选择器索引越界问题

问题根源

IndexError说明soup.select()返回了空列表,你的CSS选择器没匹配到任何元素,核心原因分三类:

  • 选择器依赖精确DOM层级(如nth-child),页面结构微调就会失效
  • 目标SVG/text元素是JS动态渲染的,requests仅能获取静态HTML,拿不到动态生成的内容
  • 部分内容被反爬策略拦截,静态HTML里未包含目标节点

分步解决方案

1. 简化CSS选择器(优先尝试)

复杂嵌套的nth-child极不稳定,换成更宽松的选择器定位目标text元素,同时添加浏览器UA头规避基础反爬:

import bs4, requests, pyperclip

# 模拟浏览器请求头
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36'
}
phone_num = pyperclip.paste()
res = requests.get(f'https://www.telguarder.com/num/00{phone_num}', headers=headers)
res.raise_for_status()  # 先确认请求是否成功
soup = bs4.BeautifulSoup(res.text, 'html.parser')

# 简化选择器:直接定位#ratingchart下svg内的text元素
elems = soup.select('#ratingchart svg text')

# 先判断列表非空再访问,避免索引越界
if elems:
    print(elems[0].text.strip())
else:
    print("未找到目标元素,可能是动态加载或选择器失效")

2. 处理动态渲染场景

如果简化选择器后仍为空列表,说明内容是JS生成的,改用selenium模拟浏览器加载完整页面:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
import pyperclip

# 无头模式启动浏览器(不显示窗口)
options = Options()
options.add_argument('--headless=new')
options.add_argument('--disable-gpu')
options.add_argument('User-Agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36')

driver = webdriver.Chrome(options=options)
try:
    phone_num = pyperclip.paste()
    driver.get(f'https://www.telguarder.com/num/00{phone_num}')
    driver.implicitly_wait(5)  # 等待元素加载
    elem = driver.find_element(By.CSS_SELECTOR, '#ratingchart svg text')
    print(elem.text.strip())
finally:
    driver.quit()

3. 额外排查点

  • 打印res.text查看是否包含目标元素的关键词,确认请求到的页面与浏览器显示一致
  • 检查页面是否有验证码等反爬验证,若有需针对性处理

内容的提问来源于stack exchange,提问作者Arthur

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 05:10:12