火狐总是弹出登陆窗口
原因:未登录
解决方法:配置火狐配置文件路径到驱动实现免登陆访问网站
#配置文件地址
profile_directory = r'C:\Users\hp\AppData\Roaming\Mozilla\Firefox\Profiles\106pt7e6.default-release'
#加载配置
profile= webdriver.FirefoxProfile(profile_directory)
driver = webdriver.Firefox(profile) # 初始化一个火狐浏览器实例:driver`
(https://www.cnblogs.com/wulixia/p/11213926.html)
InvalidSessionIdException:尝试在不建立连接的情况下运行命令
原因:过于频繁关闭页面
解决方法:屏蔽driver.close(),使用list存储页面句柄进行切换
#首页获取
h = driver.current_window_handle
.
.
#执行爬虫操作
num=driver.window_handles
#获取当前页全部句柄
print(num)
driver.switch_to_window(num[-1])
.
.
#切换后获取
zh = driver.current_window_handle
print(zh ,'---------', h)
if zh != h:
#如果不等于首页句柄则切换
#driver.close()
driver.switch_to_window(h)
time.sleep(1)
StaleElementReferenceException:查找页面元素失败
原因:各种方式的页面刷新导致页面元素丢失
解决方法:捕获异常,重新加载页面元素
try:
wait = ui.WebDriverWait(driver,10)
#product-iWrap
goods = driver.find_elements_by_class_name('product-iWrap')
wait.until(lambda driver:driver.find_element_by_class_name('product-iWrap'))
h = driver.current_window_handle
for good in goods:
time.sleep(2)
driver.execute_script("arguments[0].scrollIntoView();",good)
# 在 bc 位置单击
ActionChains(driver).move_to_element(good).click(good).perform()
self.getInfo(driver)
zh = driver.current_window_handle
print(zh ,'========', h)
#self.getInfo(driver,good)
if zh != h:
#如果不等于首页句柄则切换
driver.close()
driver.switch_to_window(h)
time.sleep(1)
#driver.close()
except StaleElementReferenceException as msg:
print('查找页面元素失败,重新载入:',msg)
wait = ui.WebDriverWait(driver,10)
#product-iWrap
goods = driver.find_elements_by_class_name('product-iWrap')
wait.until(lambda driver:driver.find_element_by_class_name('product-iWrap'))
h = driver.current_window_handle
for good in goods:
time.sleep(2)
driver.execute_script("arguments[0].scrollIntoView();",good)
# 在 bc 位置单击
ActionChains(driver).move_to_element(good).click(good).perform()
self.getInfo(driver)
zh = driver.current_window_handle
print(zh ,'========', h)
#self.getInfo(driver,good)
if zh != h:
#如果不等于首页句柄则切换
driver.close()
driver.switch_to_window(h)
time.sleep(1)
需要导入的异常模块:
from selenium.common.exceptions import StaleElementReferenceException,MoveTargetOutOfBoundsException