Selenium多元素选择Python

z31licg0  于 2022-12-13  发布在  Python
关注(0)|答案(2)|浏览(159)

我尝试提取Xpath的所有可用元素,并且我尝试了带有's'和不带's'的元素,但似乎无法使其工作。作为'Element'是正确的,但只返回我的第一个结果,而作为'Elements',它给我一个错误:“属性错误:'list'对象没有属性'find_elements'“
我的代码:从selenium.webdriver.common.by导入通过从 selenium 导入webdriver

url = 'https://automira.ro/dealeri-autorizati/lista'

PATH = 'C:\\Users\\czoca\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\Python 3.6\\chromedriver.exe'

driver = webdriver.Chrome(PATH)
driver.get(url)

driver.maximize_window()# For maximizing window
driver.implicitly_wait(100)# gives an implicit wait for 20 seconds

dealers = driver.find_elements(By.XPATH, '/html/body/div[4]/div/div[3]/div/div[1]')

for dealer in dealers:
    name = dealer.find_elements(By.XPATH, "/html/body/div[4]/div/div[3]/div/div[1]/div/div/h4/a").text
    email = dealer.find_elements(By.XPATH, '/html/body/div[4]/div/div[3]/div/div[2]/div/div/div[3]/a').text
    phone = dealer.find_elements(By.XPATH, '/html/body/div[4]/div/div[3]/div/div[2]/div/div/div[2]/a').text
    print(name,email,phone)

有什么想法吗?
谢谢你!

wlsrxk51

wlsrxk511#

find_elements方法返回一个列表对象。你可以在列表对象上迭代以获得你需要的所有元素。
对于名称中n:印刷品

6ojccjat

6ojccjat2#

在代码中,dealers返回一个WebElement列表,因此可以使用find_elements

dealers = driver.find_elements(By.XPATH, '/html/body/div[4]/div/div[3]/div/div[1]') 

for dealer in dealers:
    # you should use 'find_element' for name, email and phone
    name = dealer.find_element(By.XPATH, "/html/body/div[4]/div/div[3]/div/div[1]/div/div/h4/a").text
    email = dealer.find_element(By.XPATH, '/html/body/div[4]/div/div[3]/div/div[2]/div/div/div[3]/a').text
    phone = dealer.find_element(By.XPATH, '/html/body/div[4]/div/div[3]/div/div[2]/div/div/div[2]/a').text
    print(name,email,phone)

相关问题