Selenium获取ArtStation作品浏览量异常求助:仅调试模式可用
解决ArtStation作品页面浏览量获取问题
问题根源
- 元素加载时机不匹配:页面还未完全渲染出浏览量元素时,代码就执行了查找操作,返回空列表;调试模式下手动停顿给了页面加载时间,因此能正常获取。
- CSS选择器稳定性不足:
div.d-flex:nth-child(2) > span:nth-child(2)这类依赖位置的选择器,容易因页面布局变动失效,整合到其他项目时环境差异会触发报错。
修复方案
1. 加入显式等待机制
用WebDriverWait等待元素加载完成,确保元素可见后再获取文本:
from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC browser1.get("https://www.artstation.com/artwork/LeAN1P") try: # 最长等待10秒,直到浏览量元素可见 views_element = WebDriverWait(browser1, 10).until( EC.visibility_of_element_located((By.CSS_SELECTOR, 'div[data-test-id="artwork-stats"] span:nth-child(2)')) ) print(views_element.text) except Exception as e: print(f"获取浏览量失败: {str(e)}")
2. 使用更稳定的选择器
ArtStation作品统计区域带有data-test-id="artwork-stats"属性,基于这个属性定位能避免布局变动导致的选择器失效。
3. 处理动态加载场景
若页面采用懒加载,可先滚动到统计区域确保元素加载:
from selenium.webdriver.common.action_chains import ActionChains browser1.get("https://www.artstation.com/artwork/LeAN1P") try: stats_container = WebDriverWait(browser1, 10).until( EC.presence_of_element_located((By.CSS_SELECTOR, 'div[data-test-id="artwork-stats"]')) ) # 滚动到统计区域 ActionChains(browser1).move_to_element(stats_container).perform() # 获取浏览量文本 views_element = stats_container.find_element(By.CSS_SELECTOR, 'span:nth-child(2)') print(views_element.text) except Exception as e: print(f"获取浏览量失败: {str(e)}")
关键注意事项
- 保证浏览器驱动版本与使用的浏览器版本完全匹配,这是整合项目时常见的报错诱因。
- 若页面存在反爬限制,可适当添加随机停顿(优先用显式等待,避免固定
sleep),防止被拦截。
内容的提问来源于stack exchange,提问作者Gazaby UnkOmia
相关产品推荐
相关产品推荐

