Selenium获取元素style中background-image遇报错,求助
解决Selenium提取thumbnail元素style属性的问题
问题根源
报错为NoSuchElementException,说明代码查找./div[@class='thumbnail']元素时,当前container下不存在该元素,或是元素未加载完成就执行了查找操作。
修正方案
1. 加入显式等待保障元素加载
用Selenium的WebDriverWait等待元素出现,避免页面加载延迟导致的元素查找失败。
2. 捕获异常处理缺失元素场景
部分新闻条目可能没有thumbnail元素,直接查找会抛出异常,需用try-except块捕获,避免程序中断。
3. 提取background-image的URL
拿到style属性后,通过正则表达式提取其中的图片链接。
修正后的代码
from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC import re driver = webdriver.Chrome() driver.get("https://www.animenewsnetwork.com/") containers = driver.find_elements(By.XPATH, '//div[@class="herald box news"]') news_link_init = [] news_intro_init = [] news_full_init = [] news_image_init = [] wait = WebDriverWait(driver, 10) for container in containers: # 提取基础新闻信息 news_link = container.find_element(By.XPATH, "./div[@class='wrap']//h3/a").get_attribute("href") news_intro = container.find_element(By.XPATH, "./div[@class='wrap']//span[@class='intro']").text news_full = container.find_element(By.XPATH, "./div[@class='wrap']//span[@class='full']").text # 处理图片提取逻辑 news_image = None try: # 等待thumbnail元素加载完成 thumbnail = wait.until(EC.presence_of_element_located((By.XPATH, ".//div[@class='thumbnail']"))) style_attr = thumbnail.get_attribute("style") # 正则匹配提取图片链接 match = re.search(r'background-image:url\((.*?)\)', style_attr) if match: news_image = match.group(1).strip('"\'') except Exception: # 元素不存在或加载失败时跳过,保留空值 pass # 存入列表 news_link_init.append(news_link) news_intro_init.append(news_intro) news_full_init.append(news_full) news_image_init.append(news_image) driver.quit()
关键说明
- 显式等待:设置10秒超时,确保元素加载完成后再执行操作,比强制等待更高效灵活。
- 异常捕获:通过
try-except处理元素缺失的情况,保证循环能持续执行,不会因单个条目异常中断。 - URL提取:正则表达式
r'background-image:url\((.*?)\)'精准匹配style属性中的图片链接,再用strip去除多余的引号,得到干净的图片地址。
内容的提问来源于stack exchange,提问作者Myth Vince
相关产品推荐
相关产品推荐

