首页 > 解决方案 > 使用 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)(第一个)中提到的第一个链接

标签: pythonseleniumselenium-webdriver

解决方案


推荐阅读