使用Selenium Python爬取站点时出现NameError: name 'teams' is not defined报错
问题原因及解决方案
无输出问题原因
你删除print代码后程序无输出是正常现象:你的代码除了print语句外没有任何写入文件、输出日志的逻辑,程序执行完全部操作后无报错正常退出,就只会返回process finished with exit code 0的提示,不会有其他输出。
NameError报错原因
- 第一是缩进错误:你当前的
print(teams,odds)写在for循环外部,只要box元素列表为空,for循环完全不会执行,teams和odds变量根本不会被定义,调用时就会触发未定义报错。即使box不为空,写在循环外也只会打印循环最后一次的执行结果,不符合遍历取值的需求。 - 第二是元素定位规则错误:
find_elements_by_class_name方法仅支持传入单个类名,你传入了多个用空格分隔的类名,会直接导致定位失败,返回的box是空列表,for循环不会执行。 - 附加说明:你使用的
find_elements_by_*是Selenium 3的旧写法,Selenium 4+版本已弃用该系列API,建议统一使用find_elements(By.XXX, 选择器)的写法。
修正后的参考代码
from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.common.by import By options = Options() options.headless = False web = 'https://fezbet1.com/en/sport?sportids=1' path = r'C:\Users\Senne\Desktop\Chromedriver\chromedriver.exe' options.add_argument('window-size=1920x1080') driver = webdriver.Chrome(path, options=options) driver.get(web) driver.maximize_window() driver.implicitly_wait(10) frame_ref = driver.find_elements(By.TAG_NAME, "iframe")[1] driver.switch_to.frame(frame_ref) # 用css选择器定位多类名元素 box = driver.find_elements(By.CSS_SELECTOR, '.asb-flex-col.asb-cut.asb-pos-wide._asb_events-table-row') # 先判断列表是否为空 if not box: print("未定位到目标元素列表") else: for data in box: # 建议简化xpath,避免用过长的绝对路径,容易随页面结构变化失效 try: teams = data.find_element(By.XPATH, './/*[@id="sb"]/div[2]/div[2]/div[2]/div[3]/div/div[1]/div/div[2]/div[1]/div/div/div[2]/div[1]/div/div[2]/div/div/div[2]/div[1]').text odds = data.find_element(By.XPATH, './/*[@id="sb"]/div[2]/div[2]/div[2]/div[3]/div/div[1]/div/div[2]/div[1]/div/div/div[2]/div[2]/div[1]/div[1]/div/div[2]/div').text # print缩进放到循环内部 print(teams, odds) except Exception as e: print(f"当前元素取值失败:{str(e)}") driver.quit()
注意:爬取未获得官方授权的站点可能违反目标站点的使用协议及当地相关法律法规,请合规使用爬虫技术。
内容的提问来源于stack exchange,提问作者Senne Van De Perre
相关产品推荐
相关产品推荐

