Проблемы с утилизацией Tripadvisor с Selenium - PullRequest
0 голосов
/ 19 января 2020

У меня есть этот Python код для удаления веб-сайта TripAdvisor, и до прошлого года (18 дней go) код работал потрясающе, но теперь код не работает должным образом, и я получаю этот результат (показано выше) )

Я пытаюсь с изменениями, как это container = driver.find_elements_by_xpath("//div[@class='data-test-target']") Но не работает. Также я отметил, что теперь на сайте нет элемента taLnk ulBlueLinks или элемента review-container.

Пожалуйста, если вы можете помочь мне с кодом, это будет фантазия c.

PD: Кроме того, я пробовал с красивым супом, но код все равно не работает.


import csv
import time
from selenium import webdriver
import datetime
from selenium.common.exceptions import NoSuchElementException

#Common
now = datetime.datetime.now()
driver = webdriver.Chrome('chromedriver.exe')
italia = "https://www.tripadvisor.it/Attraction_Review-g657290-d2213040-Reviews-Ex_Stabilimento_Florio_delle_Tonnare_di_Favignana_e_Formica-Isola_di_Favig.html"
driver.get(italia)

place = 'Ex_Stabilimento_Florio_delle_Tonnare_di_Favignana'
lang = 'it'


def check_exists_by_xpath(xpath):
    try:
        driver.find_element_by_xpath(xpath)
    except NoSuchElementException:
        return False
    return True





for i in range(0, 2):
    try:
        if (check_exists_by_xpath("//span[@class='taLnk ulBlueLinks']")):
            driver.find_element_by_xpath("//span[@class='taLnk ulBlueLinks']").click()
            time.sleep(5)
        container = driver.find_elements_by_xpath("//div[@class='review-container']")

        num_page_items = len(container)
        for j in range(num_page_items):

            csvFile = open(r'Italia_en.csv', 'a')
            csvWriter = csv.writer(csvFile)

            time.sleep(10)
            rating_a = container[j].find_element_by_xpath(
                ".//span[contains(@class, 'ui_bubble_rating bubble_')]").get_attribute("class")
            rating_b = rating_a.split("_")
            rating = rating_b[3]

            review = container[j].find_element_by_xpath(".//p[@class='partial_entry']").text.replace("\n", "")
            title = container[j].find_element_by_class_name('quote').find_element_by_tag_name(
                'a').find_element_by_class_name('noQuotes').text

            print(review)
            rating_date = container[j].find_element_by_class_name('ratingDate').get_attribute('title')
            print(rating, review, title, "--", sep='\n')
            link_list = []
            for link in container[j].find_elements_by_tag_name('a'):
                link_previous = (link.get_attribute('href'))
                link_list.append(link_previous)

            print(link_list[1], "--", sep='\n')

            csvWriter.writerow([place, rating, title, review, rating_date, link_list[1], now, lang])

        driver.find_element_by_xpath('//a[@class="nav next taLnk ui_button primary"]').click()

        time.sleep(5)

    except:

        driver.find_element_by_xpath('//a[@class="nav next taLnk ui_button primary"]').click()
        time.sleep(5)

И результат

    Traceback (most recent call last):
  File "gh_code2.py", line 63, in <module>
    driver.find_element_by_xpath('//a[@class="nav next taLnk ui_button primary"]').click()
  File ".\Programs\Python\Python37\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 394, in find_element_by_xpath
    return self.find_element(by=By.XPATH, value=xpath)
  File ".\Programs\Python\Python37\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 978, in find_element
    'value': value})['value']
  File ".\Programs\Python\Python37\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute
    self.error_handler.check_response(response)
  File ".\Programs\Python\Python37\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//a[@class="nav next taLnk ui_button primary"]"}
  (Session info: chrome=79.0.3945.117)


During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "gh_code2.py", line 69, in <module>
    driver.find_element_by_xpath('//a[@class="nav next taLnk ui_button primary"]').click()
  File ".\Programs\Python\Python37\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 394, in find_element_by_xpath
    return self.find_element(by=By.XPATH, value=xpath)
  File ".\Programs\Python\Python37\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 978, in find_element
    'value': value})['value']
  File ".\Programs\Python\Python37\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute
    self.error_handler.check_response(response)
  File ".\Programs\Python\Python37\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//a[@class="nav next taLnk ui_button primary"]"}
  (Session info: chrome=79.0.3945.117)

1 Ответ

0 голосов
/ 19 января 2020

К сожалению, по моему опыту с чисткой сайтов, если сайт обновлен и эти ссылки на xpath пропали, вы должны обновить свой скрипт. В этом случае кажется, что

class="nav next taLnk ui_button primary"

больше не является жизнеспособным селектором. Если это общая ссылка со схожей структурой со временем, я бы попытался использовать итерации, а не точное имя класса. то есть навигационная кнопка [0] или что-то в этом роде (точный синтаксис передо мной отсутствует).

В противном случае, проверьте FireFox браузер selenium IDE. Это может помочь вам найти другие способы ссылки на элементы при переходе по сайту.

Надеюсь, что это некоторая справка!

...