使用python+selenium爬虫时遇到的一些问题

火狐总是弹出登陆窗口

原因:未登录

解决方法:配置火狐配置文件路径到驱动实现免登陆访问网站

在这里插入图片描述
在这里插入图片描述

#配置文件地址
profile_directory = r'C:\Users\hp\AppData\Roaming\Mozilla\Firefox\Profiles\106pt7e6.default-release'   
#加载配置
profile= webdriver.FirefoxProfile(profile_directory)
driver = webdriver.Firefox(profile) # 初始化一个火狐浏览器实例:driver`

Chrome和Firefox浏览器驱动下载及配置文件加载

(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
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值