xpath - 单击所有按钮

时间:2021-07-25 06:35:16

标签: javascript python selenium xpath

我的代码进入一个网页,这个网页有几行记录。单击时,每一行都会显示一个下拉列表。

我的代码启动了一次点击,但出于某种原因只针对网页的第一行

当我的代码遇到每条记录时,我如何才能执行单击操作。不仅仅是第一次进入?

from selenium import webdriver
from bs4 import BeautifulSoup
import time
driver = webdriver.Chrome()

driver.get(f'https://library.iaslc.org/conference-program?product_id=24&author=&category=&date=&session_type=&session=&presentation=&keyword=&available=&cme=&page=1')
time.sleep(4)
page_source = driver.page_source
soup = BeautifulSoup(page_source,'html.parser')
productlist=soup.find_all('div',class_='accordin_title')
for j in productlist:
    title=j.find('h4').text.strip()
    buttonToClick=driver.find_element_by_class_name('sign')
    buttonToClick.click()
    time.sleep(5)    

1 个答案:

答案 0 :(得分:1)

driver.find_element_by_class_name('sign') 命令在整个页面上搜索第一个具有 sign 类名的元素。这就是为什么这总是会给你相同的,第一个元素。而您应该在j元素内部搜索。
h4 标题也是如此。
为了获得标题并点击里面的按钮,手风琴试试这个:

productlist=soup.find_all('div',class_='accordin_title')
for j in productlist:
    title=j.find_element_by_xpath('.//h4').text.strip()
    buttonToClick=j.find_element_by_xpath('.//div[@class="sign"]')
    buttonToClick.click()
    time.sleep(5)    

UPD
让我们试试纯硒解决方案

driver.get(f'https://library.iaslc.org/conference-program?product_id=24&author=&category=&date=&session_type=&session=&presentation=&keyword=&available=&cme=&page=1')
time.sleep(4)

productlist_length = len(driver.find_elements_by_xpath("//div[@class='accordin_title']"))
for i in range(1, productlist_length+1):
    product = driver.find_element_by_xpath("(//div[@class='accordin_title'])[" + str(i) + "]")
    title = product.find_element_by_xpath('.//h4').text.strip()
    print(title)
    buttonToClick=product.find_element_by_xpath('.//div[@class="sign"]')
    buttonToClick.click()
    time.sleep(5)