无法使用selenium单击迭代元素

时间:2016-10-09 15:19:12

标签: python selenium web-scraping

我试图点击迭代google-translate元素,但代码无效

from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Chrome()
driver.get("https://www.tripadvisor.com.br/ShowUserReviews-g1-d8729164-r425802060-TAP_Portugal-World.html")
for i in driver.find_elements_by_class_name("entry"):
wait = WebDriverWait(driver, 10)

google_translate = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, ".googleTranslation .link")))

actions = ActionChains(driver)
actions.move_to_element(google_translate).click().perform()
driver.find_element_by_class_name("ui_close_x").click()
driver.execute_script("window.scrollTo(0, 600);")

======= ISSUE ====== 它仅通过第一个元素迭代

基本上,代码应该在弹出窗口中显示每个评论的翻译,关闭弹出窗口,然后转到下一个评论,翻译等

1 个答案:

答案 0 :(得分:1)

from selenium import webdriver
from selenium.webdriver.common.by import By
import time

driver = webdriver.Chrome()
driver.maximize_window()
driver.get("https://www.tripadvisor.com.br/ShowUserReviews-g1-d8729164-r425802060-TAP_Portugal-World.html")
gt= driver.find_elements(By.CSS_SELECTOR,".googleTranslation>.link")
for i in gt:
    i.click()
    time.sleep(2)
    driver.find_element_by_class_name("ui_close_x").click()
    time.sleep(2)

The above code will solve your purpose of clicking on each review google translate. PS: in For loop i have placed the time.sleep() so that you can see the code action, if you want you can remote it