웹 스크래핑 중 NoSuchElementException 및 SyntaxError

Sep 01 2020

이 제안을 적용하여 다음 오류를 수정하는 데 어려움이 있습니다.

NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"./ancestor-or-self::form"}

다음 코드를 사용할 때 얻었습니다.

from selenium import webdriver

query = ' I want to try to translate this text'
chrome_options = webdriver.ChromeOptions('/chromedriver')
driver = webdriver.Chrome()
driver.get('https://translate.google.com/')
search = driver.find_element_by_css_selector('#source')
search.send_keys(query)
search.submit()

여기에 설명 된대로 : NoSuchElementException-요소를 찾을 수 없습니다. 다음과 같이 사용해야합니다.

WebDriverWait wait = new WebDriverWait(driver, 10);

wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt("source"));

하지만 (때문에 WebDriverWait wait =) SyntaxError가 발생합니다 .

나는 또한 다음 답변을 따르려고 노력했습니다.

NoSuchElementException (SyntaxError : 정적으로 중첩 된 블록이 너무 많음)

Selenium Webdriver-NoSuchElementExceptions

하지만 여전히 오류가 발생합니다.

try:
    search = driver.find_element_by_css_selector('#source')

    break
except NoSuchElementException:
    time.sleep(1)

나에게 준다 break outside the loop; 반면 이것은

try:
    search = driver.find_element_by_css_selector('#source')

except NoSuchElementException:         
    pass

아무것도 변경하지 않습니다 (여전히 오류가 발생합니다. NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"./ancestor-or-self::form"})

이 오류를 수정하는 방법을 찾도록 도와 주시겠습니까?

업데이트 : 나도 사용하려고했는데 driver.implicitly_wait(60)같은 NoSuchElementExpection오류가 발생했습니다.

오류에 대한 자세한 내용 :

---> 23     search.submit()
     24 
     25 

~/anaconda3/lib/python3.7/site-packages/selenium/webdriver/remote/webelement.py in submit(self)
     83         """Submits a form."""
     84         if self._w3c:
---> 85             form = self.find_element(By.XPATH, "./ancestor-or-self::form")
     86             self._parent.execute_script(

답변

rahulrai Sep 02 2020 at 04:59

다음 줄을 제외하고 맨 위에 공유 된 코드에서 모든 작업을 수행 search.submit()했습니다.. 당신이 전화하는 것처럼 submit()당신에 의해 정의 된 웹 요소와 요소 검색 방법을 어떤 형태 오히려 그 없습니다 Textarea따라서 NoSuchElementException. 제출 방법은 form요소 유형 에만 적용 가능하기 때문 입니다. 이 줄을 제거하면 코드가 잘 작동합니다.

셀레늄 가져 오기 웹 드라이버에서

query = ' I want to try to translate this text'
chrome_options = webdriver.ChromeOptions('/chromedriver')
driver = webdriver.Chrome()
driver.get('https://translate.google.com/')
search = driver.find_element_by_css_selector('#source')
search.send_keys(query)

산출

노트 :

셀레늄 파이썬에서 다른 대기 메커니즘을 사용하는 방법을 알고 싶다면 아래를 읽어보십시오.

https://selenium-python.readthedocs.io/waits.html

ArundeepChohan Sep 02 2020 at 02:16
<textarea id="source" class="orig tlid-source-text-input goog-textarea" rows="1" spellcheck="false" autocapitalize="off" autocomplete="off" autocorrect="off" style="overflow: auto hidden; box-sizing: border-box; height: 70px; padding-bottom: 18px;"></textarea>

Xpath는 다음 중 하나 일 수 있습니다.

//*[@id='source']

/html/body/div[2]/div[2]/div[1]/div[2]/div[1]/div[1]/div[1]/div[2]/div/div/div[1]/textarea

기본적으로 요소를 기다리고 쿼리를 보내고 제출을 누르십시오.

search = WebDriverWait(driver, 10).until( 
        EC.presence_of_element_located((By.XPATH, //*[@id='source'])) 
search.send_keys(query)
search.submit()

또한 추가하십시오

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