python - 使用 selenium Python 迭代不同的元素
问题描述
我的问题是,当我的循环只迭代一次时,我想通过我列出的所有元素,如果您有任何可以帮助的建议。这是我的代码,你可以测试它的工作,所以如果你能建议我任何切换窗口的方法,我试过driver.back()
了,但它没有解决我的问题
from time import sleep
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
import bs4 as bs
import pandas as pd
options = Options()
# Creating our dictionary
# all_services = pd.DataFrame(columns=['Profil', 'Motif', 'Questions', 'Reponses'])
Testing = pd.DataFrame(columns=['Motif', 'Resultat'])
path = "C:/Users/Al4D1N/Documents/ChromeDriver_webscraping/chromedriver.exe"
driver = webdriver.Chrome(options=options, executable_path=path)
# we are going to visit all profils procedures
# for profil in ['particuliers','professionnels','associations']:
# driver.get(f"https://www.demarches.interieur.gouv.fr/{profil}/accueil-{profil}")
driver.get("https://www.demarches.interieur.gouv.fr/associations/accueil-associations")
sleep(3)
# Get all first elements in bodyFiche id which contains all procedures for associations profile
list_of_services = driver.find_elements_by_class_name("liste-sous-menu")
for service in list_of_services:
# In each element, select the tags
# atags = service.find_elements_by_css_selector('a')
atags = service.find_elements_by_xpath("//li[starts-with(@id,'summary')]/a")
for atag in atags:
# In each atag, select the href
href = atag.get_attribute('href')
# Open a new window
driver.execute_script("window.open('');")
# Switch to the new window and open URL
driver.switch_to.window(driver.window_handles[1])
driver.get(href)
sleep(3)
# we are now on the second link
# Get all links in the iterated element
list_of_services2 = driver.find_elements_by_class_name("content")
for service2 in list_of_services2:
atags2 = service2.find_elements_by_css_selector('a')
for atag2 in atags2:
href = atag2.get_attribute('href')
driver.execute_script("window.open('');")
driver.switch_to.window(driver.window_handles[1])
driver.get(href)
sleep(3)
# Close the tab with URL B
driver.close()
# Switch back to the first tab with URL A
driver.switch_to.window(driver.window_handles[0])
driver.close()
Testing.to_excel('Limit_Testing.xlsx', index=False)
我怎样才能通过我得到的链接,用一种driver
方法,因为像那样运行它,它只是迭代一个元素,它会回到driver.get(url)
(第一个)中提到的第一个链接
解决方案
推荐阅读
- python - 需要以下格式的 Python 熊猫
- jestjs - 使用 Jest 测试 NestJS + TypeORM 时“'instanceof' 的右侧不是对象”
- docker - 如何通过 cli 检查 Docker Swarm 资源预留
- python - 为什么 ipywidgets 的小部件没有在 html 文件中定义?
- c++ - 使用 Playsound c++ 在后台运行音乐
- spring-boot - Spring boot oauth2 客户端凭据使用 webflux 动态配置
- python - 切片列表以提取给定索引的最后 k 和下 k 元素
- reactjs - 在 Docker 上运行 CRA 时出现错误(0,_schemaUtils.default)不是函数
- r - 将一个字符添加到 R 中向量列表中的每个向量
- node.js - 如何将数组添加到存在于 mongodb 对象中的另一个数组中