点击迭代在selenium中失败

时间:2016-10-10 05:28:07

标签: python selenium web-scraping

我试图从tripadvisor翻译用户评论。因此,刮刀读取链接,然后逐个遍历每个注释并翻译它们。但是我的代码在翻译第一个评论后就停止了。

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

driver = webdriver.Chrome()
driver.maximize_window()
driver.get("https://www.tripadvisor.in/ShowUserReviews-g1-d8729164-r425811350-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)

2 个答案:

答案 0 :(得分:1)

试试这个:

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

driver = webdriver.Chrome()
driver.maximize_window()
url="https://www.tripadvisor.com/Airline_Review-d8729164-Reviews-Cheap-Flights-TAP-Portugal#REVIEWS"
driver.get(url)

wait = WebDriverWait(driver, 10)

langselction = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "span.sprite-date_picker-triangle")))
langselction.click()
driver.find_element_by_xpath("//div[@class='languageList']//li[normalize-space(.)='Portuguese first']").click()
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)

答案 1 :(得分:1)

我试过你的相同代码只是增加了睡眠时间,列表越过列表并且评论也被翻译了

注意:我在Firefox上试过这个程序

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

driver = webdriver.Firefox()
driver.maximize_window()
driver.get("https://www.tripadvisor.in/ShowUserReviews-g1-d8729164-r425811350-TAP_Portugal-World.html")
gt= driver.find_elements(By.CSS_SELECTOR,".googleTranslation>.link")
print(type(gt))
for i in gt:
    i.click()
    time.sleep(15)
    driver.find_element_by_class_name("ui_close_x").click()
    time.sleep(15)