python-3.x - 在循环中获取元素的 Selenuim Python 问题
问题描述
soup = BeautifulSoup(browser.page_source, "html.parser")
for h1 in soup.find_all('h2'):
try:
array.append("https://www.chamberofcommerce.com" + h1.find("a")['href'])
print("https://www.chamberofcommerce.com" + h1.find("a")['href'])
except:
pass
input=browser.find_element_by_xpath('//a[@class="next"]')
while input:
input.click()
time.sleep(10)
soup = BeautifulSoup(browser.page_source, "html.parser")
for h1 in soup.find_all('h2'):
try:
array.append("https://www.chamberofcommerce.com" + h1.find("a")['href'])
print("https://www.chamberofcommerce.com" + h1.find("a")['href'])
except:
pass
这部分代码在yellopages上删除了列表的url,代码运行良好,直到我过去只从搜索的第一页删除url,现在我希望它点击下一步按钮,直到搜索页面完成,敌人示例如果有 20 页的搜索,那么 selenuim 机器人应该点击下一步按钮并删除 url,直到它到达第 20 页,
请查看代码的逻辑,并且在机器人到达第 2 页后我收到以下错误,因为实际页数为 15,并且它在第 2 页崩溃:
selenium.common.exceptions.StaleElementReferenceException: Message: stale element reference: element is not attached to the page document
解决方案
while input
不是您需要的...请注意,单击“下一步”按钮后,将加载新页面,并且上一页中的所有 WebElement 都不再有效:您必须在每个页面上重新定义它们。尝试以下方法:
while True:
try:
browser.find_element_by_xpath('//a[@class="next"]').click()
except:
break
使用上面的代码,您应该能够在每个页面可用时单击“下一步”按钮。您可能还需要应用ExplicitWait来等待 Next 按钮可点击:
wait.until(EC.element_to_be_clickable((By.XPATH, '//a[@class="next"]'))).click()
推荐阅读
- performance - Jenkins - jmeter 性能插件 - 构建步骤“发布性能测试结果报告”将构建结果更改为 FAILURE Finished: FAILURE
- sql - Datediff 函数导致两个日期 Minute Diff 溢出(没有 DateDiff_Big)
- java - Hibernate 中的 ObjectNotFoundException:不存在具有给定标识符的行
- excel - 条件高亮:如何优化?
- hive - AWS EMR 上的 Hive 不起作用
- angularjs - 编译的动态模板无法访问 ng-controller 函数
- html - 查看个人资料图片
- xml - 用 XSLT 替换 xml 中的 break 元素
- azure - 数据盘是干什么用的?
- pyqt - 调整自定义 QTableWidget 的大小(宽/高)