Python中selenium模块在for循环下模拟点击只执行一次的问题如何解决?
coding=utf-8
from lxml import etree
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
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver import ActionChains
import time
driver = webdriver.Chrome()
driver.get(‘https://www.manhuatai.com/fengqicanglan/115hs.html’)
menu = driver.find_element_by_css_selector(".mh_nextpage")
actions = ActionChains(driver)
for i in range(3):
# 智能等待
try:
element = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, “comiclist”)))
except NoSuchElementException:
print(‘找不到元素异常’)
# 获取图片链接
res = driver.page_source
html = etree.HTML(res)
pictrue_url = html.xpath(’//div[@class=“mh_comicpic”]/img/@src’)[0]
print(pictrue_url)
# 在“下一页”位置点击鼠标左键
actions.click(menu)
actions.perform()
driver.close()
Python中selenium模块在for循环下模拟点击只执行一次的问题如何解决?
5 回复
不知道是不是手机的原因,看不到缩进啊
猜测是 acctions.click 这句有问题吧
需要清一下之前的 action 队列的
不久前遇到过这个问题
action.reset_actions()一下
现在还是没搞明白,为啥,但是我改了下代码,将下面的这几句都删了
=========
menu = driver.find_element_by_css_selector(".mh_nextpage")
actions = ActionChains(driver)
# 在“下一页”位置点击鼠标左键
actions.click(menu)
actions.perform()
=========
在 for 循环最下面加了里最下面
driver.find_element_by_css_selector(".mh_nextpage").click()
对标签用.click()是实时执行的
而 action_chain 是先构建一个队列,执行 actions.perform 的时候执行队列
如果队列不清空的话队列会员一直累积 每次循环都会向队列新增动作且保留之前的动作


