I dont know where the problem is
I used theese sources
https://medium.com/python/python-selenium-mod%C3%BCl%C3%BC-kullan%C4%B1m%C4%B1-ders-1-36983185164c
https://www.youtube.com/watch?v=olOswIyeRlY
Code
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
driver_path = r"C:\Users\ruzgaricatsirketi\Desktop\chromedriver_win32\chromedriver.exe"
driver = webdriver.Chrome(executable_path=driver_path)
driver.get("https://translate.google.com/#tr/tr")
dinle = driver.find_element_by_id('gt-speech')
dinle.click()
time.sleep(2)
dinle.click()
time.sleep(3)
getir = driver.find_element_by_id('result_box').text
print(getir)
Error
DevTools listening on ws://127.0.0.1:12239/devtools/browser/76eb55d7-8aef-4b19-9d6e-fda8f4f1aee4
Traceback (most recent call last):
File "C:\Users\ruzgaricatsirketi\Desktop\test.py", line 13, in <module>
getir = driver.find_element_by_id('result_box').text
File "C:\Users\ruzgaricatsirketi\AppData\Local\Programs\Python\Python37-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 360, in find_element_by_id
return self.find_element(by=By.ID, value=id_)
File "C:\Users\ruzgaricatsirketi\AppData\Local\Programs\Python\Python37-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 978, in find_element
'value': value})['value']
File "C:\Users\ruzgaricatsirketi\AppData\Local\Programs\Python\Python37-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute
self.error_handler.check_response(response)
File "C:\Users\ruzgaricatsirketi\AppData\Local\Programs\Python\Python37-32\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":"id","selector":"result_box"}
(Session info: chrome=78.0.3904.97)
(Driver info: chromedriver=2.35.528161 (5b82f2d2aae0ca24b877009200ced9065a772e73),platform=Windows NT 10.0.18362 x86_64)
In order to work with Python correctly, it is crucial to learn to read the stack trace. In your case, these lines
File "C:\Users\ruzgaricatsirketi\Desktop\test.py", line 13, in <module>
getir = driver.find_element_by_id('result_box').text
say that the exception has its origin on line 13 in your file test.py, where you are trying to search for web element with id attribute set to value "result_box". Exception you have got is NoSuchElementException:
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"id","selector":"result_box"}
As you can find in official documentation or many other places (and I bet there are thousands of them), this exception is raised when the element you are searching for is not found.
Try it yourself — open your tested Google Translator page and try to search for element with any existing id. E.g. on line 8 in your test file you are trying to locate element with id "gt-speech". Write document.getElementById("gt-speech") to your browsers console and whoala! It works, this node matches your search:
<div id="gt-speech" class="speech-button goog-toolbar-button"...>...</div>
Note especially the id="gt-speech" attribute, it is the one selenium will use to identify the object. However, if you try the same with id "result_box", you will get nothing (null is returned if using JS console to search for element), because there is no such element on the page (thus NoSuchElementException...).
My advice for you:
inspect the element you are trying to locate (on the most of the popular web browsers on Windows/Linux systems it is as easy as right-clicking the element and selecting the inspect option)
select some unique properties, you can use also other properties than id (preferably not inner text; IDs are best, but they are not always present...)
use those properties to find the element using selenium
And please, next time try to search a bit on your own before you ask, because this is some really really trivial problem you should be able to handle after first 5 minutes of any selenium course (in other words, UTFG :P)
EDIT
P.S. I can see you have got that invalid id from the video you have marked as your source. The fact that element with such id was present one year ago does not mean it will be there forever (an for every platform). If you need to get that certain element, you have to find another way how to define it using selenium locators I have mentioned earlier.
Related
I am using Python3.9+Selenium to write a small script that fills an online form for me.
A bit of context: the webpage contains a field (locationField) expecting a street address as input, and located on top of some sort of "google maps wrapper".
When typing in the field, it loads a drop-down list of one element (locationField_sugg) with the compatible complete address, and when this option is selected the map zooms-in on the chosen part of the city.
Other than this, there is a descriptionField to be filled with some random text, and then a submitButton to be clicked in order to send the form.
I noticed that if I use actionChains.move_to_element(locationField_sugg).click().perform() to click on the address in the drop-down list, then submitButton throws a StaleElementReference exception, while if I just use locationField_sugg.click() this is not the case, and the code proceeds as it should.
I've been reading through many Q/A about this notorious exception handling, but none of them seemed to explain the reason why this happens in my code.
For me it seems to be related to the behaviour of move_to_element() in combination with the "map wrapper" (?) but I do not understand why, since this function is just supposed to move the mouse in the middle of a given element.
No reload nor other changes in the webpage seem to happen (I verified that if I query the button at the beginning and re-query at the end of the script, I get the same exact instance representation string).
Besides, I query the submitButton right before performing an action on it, and I assume it is properly found since it can be printed.
Below there is a snippet of my code and of the output I get (Note: the code works properly if I use the alternative commented option, but I am curious to understand what I am missing)
CODE SNIPPET
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
websiteUrl = "https://mywebsite"
option = webdriver.ChromeOptions()
option.add_argument("-incognito")
browser = webdriver.Chrome(executable_path="/Applications/chromedriver", options=option)
browser.get(websiteUrl)
actionChains = ActionChains(browser)
# Write and select complete address
locationField = browser.find_element_by_id("location")
print("locationField = ", locationField)
locationField.send_keys("my location")
locationField_sugg = WebDriverWait(browser, 10).until(EC.visibility_of_element_located((By.ID, "as-listbox")))
print("locationField_sugg = ", locationField_sugg)
#
# this throws stale element reference exception:
actionChains.move_to_element(locationField_sugg).click().perform()
#
# this does not:
# locationField_sugg.click()
# Write description
descriptionField = browser.find_element_by_id("description")
print("descriptionField = ", descriptionField)
descriptionField.send_keys("my description")
# Submit form
submitButton = WebDriverWait(browser, 10).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "span.value")))
print("submitButton = ", submitButton)
actionChains.move_to_element(submitButton).click().perform()
OUTPUT
locationField = <selenium.webdriver.remote.webelement.WebElement (session="e10dc716790c61a0c160599624dd30c6", element="e75539a7-ebd0-4090-9c04-0c4994afe03f")>
locationField_sugg = <selenium.webdriver.remote.webelement.WebElement (session="e10dc716790c61a0c160599624dd30c6", element="53ef0269-aceb-451a-b559-d9e5e7aa7851")>
descriptionField = <selenium.webdriver.remote.webelement.WebElement (session="e10dc716790c61a0c160599624dd30c6", element="dce478de-a23d-4ca2-817c-81ee5ce0c232")>
nowButton = <selenium.webdriver.remote.webelement.WebElement (session="e10dc716790c61a0c160599624dd30c6", element="f2036f1c-d164-4211-a37c-2ee50e5c55c1")>
Traceback (most recent call last):
File "/Users/alice/Desktop/wasteComplaints_selenium.py", line 44, in <module>
actionChains.move_to_element(nowButton).click().perform()
File "/Users/alice/miniconda3/lib/python3.9/site-packages/selenium/webdriver/common/action_chains.py", line 80, in perform
self.w3c_actions.perform()
File "/Users/alice/miniconda3/lib/python3.9/site-packages/selenium/webdriver/common/actions/action_builder.py", line 76, in perform
self.driver.execute(Command.W3C_ACTIONS, enc)
File "/Users/alice/miniconda3/lib/python3.9/site-packages/selenium/webdriver/remote/webdriver.py", line 321, in execute
self.error_handler.check_response(response)
File "/Users/alice/miniconda3/lib/python3.9/site-packages/selenium/webdriver/remote/errorhandler.py", line 242, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.StaleElementReferenceException: Message: stale element reference: element is not attached to the page document
(Session info: chrome=92.0.4515.131)
I'm not sure I know why this occurs without debugging it. Maybe the suggested address is disappearing at the moment when focus is removed from the input field? If so, when you insert the address string to the input field and then instantly clicking on the suggested address it works correct, but if after inserting the input address string and the suggested address appears you are applying actionChains.move_to_element this moves the mouse from it's initial position to the suggested address element. So the focus is moved from input field to the mouse cursor. This causes the suggested address to disappear and this is why StaleElementReference exception is thrown.
EDITED: I incorporated the final lines suggested by Sushil. At the end, I am copying the output in my terminal. I still do not get the zipfile.
SOLVED: My error was due to an incompatibility between the driver and chrome versions. I fixed by following the instructions here: unknown error: call function result missing 'value' for Selenium Send Keys even after chromedriver upgrade
I am trying to use Selenium to fill out a form and download a zipfile.
After extensively googling, I have written a Python code, but I am currently unable to download the file. A browser opens, but nothing is filled out.
I am very new at Python, so I am guessing I am missing something very trivial since the website I am trying to get info from is super simple.
This is what I have tried:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver = webdriver.Chrome(executable_path='/home/miranda/webscrap_Python/chromedriver')
#driver.wait = WebDriverWait(driver,5)
driver.get("http://www.cis.es/cis/opencms/EN/formulario.jsp?dwld=/Microdatos/MD3288.zip")
Name = '//*[#id="Nombre"]'
LastName = '//*[#id="Apellidos"]'
University = '//*[#id="profesion"]'
email = '//*[#id="Email"]'
ob_req = '//*[#id="objeto1"]'
terms = '//*[#id="Terminos"]'
download = '//*[#id="mediomicrodatos"]/form/div[3]/input'
driver.find_element_by_xpath(Name).send_keys("Miranda")
driver.find_element_by_xpath(LastName).send_keys("MyLastName")
driver.find_element_by_xpath(University).send_keys("MySchool")
driver.find_element_by_xpath(email).send_keys("my_email#gmail.com")
#lines added by Sushil:
ob_req_element = driver.find_element_by_xpath(ob_req) #Finds the ob_req element
driver.execute_script("arguments[0].click();", ob_req_element) #Scrolls down to the element and clicks on it
terms_element = driver.find_element_by_xpath(terms) #The same is repeated here
driver.execute_script("arguments[0].click();", terms_element)
driver.find_element_by_xpath(download).click() #Scrolling down is not needed for the download button as it would already be in view. Only when an element is not in view should we scroll down to it in order to click on it.
Output in my terminal:
Traceback (most recent call last):
File "myCode.py", line 18, in <module>
driver.find_element_by_xpath(Name).send_keys("Miranda")
File "/home/miranda/anaconda3/lib/python3.7/site-packages/selenium/webdriver/remote/webelement.py", line 479, in send_keys
'value': keys_to_typing(value)})
File "/home/miranda/anaconda3/lib/python3.7/site-packages/selenium/webdriver/remote/webelement.py", line 633, in _execute
return self._parent.execute(command, params)
File "/home/miranda/anaconda3/lib/python3.7/site-packages/selenium/webdriver/remote/webdriver.py", line 321, in execute
self.error_handler.check_response(response)
File "/home/miranda/anaconda3/lib/python3.7/site-packages/selenium/webdriver/remote/errorhandler.py", line 242, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.WebDriverException: Message: unknown error: call function result missing 'value'
(Session info: chrome=86.0.4240.75)
(Driver info: chromedriver=2.29.461571 (8a88bbe0775e2a23afda0ceaf2ef7ee74e822cc5),platform=Linux 5.4.0-45-generic x86_64)
For each and every element below the email element, you have to scroll down to click them. Here is the full code to do it:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver = webdriver.Chrome()
#driver.wait = WebDriverWait(driver,5)
driver.get("http://www.cis.es/cis/opencms/EN/formulario.jsp?dwld=/Microdatos/MD3288.zip")
Name = '//*[#id="Nombre"]'
LastName = '//*[#id="Apellidos"]'
University = '//*[#id="profesion"]'
email = '//*[#id="Email"]'
ob_req = '//*[#id="objeto1"]'
terms = '//*[#id="Terminos"]'
download = '//*[#id="mediomicrodatos"]/form/div[3]/input'
driver.find_element_by_xpath(Name).send_keys("Miranda")
driver.find_element_by_xpath(LastName).send_keys("MyLastName")
driver.find_element_by_xpath(University).send_keys("MySchool")
driver.find_element_by_xpath(email).send_keys("my_email#gmail.com")
#All the lines below were added by me
ob_req_element = driver.find_element_by_xpath(ob_req) #Finds the ob_req element
driver.execute_script("arguments[0].click();", ob_req_element) #Scrolls down to the element and clicks on it
terms_element = driver.find_element_by_xpath(terms) #The same is repeated here
driver.execute_script("arguments[0].click();", terms_element)
driver.find_element_by_xpath(download).click() #Scrolling down is not needed for the download button as it would already be in view. Only when an element is not in view should we scroll down to it in order to click on it.
I tried Most of the solution of StackOverflow but didn't work for me
I am trying to send some course name to youtube search bar using selenium python it works fine before but now it gives this error while doing this
And search_bar.send_keys(course_name) works fine for other websites but not in YT
Traceback (most recent call last):
File "src/gevent/greenlet.py", line 766, in gevent._greenlet.Greenlet.run
File "/home/sh4d0w/PycharmProjects/AutoMate/venv/lib/python3.7/site-packages/eel/__init__.py", line 257, in _process_message
return_val = _exposed_functions[message['name']](*message['args'])
File "/home/sh4d0w/PycharmProjects/AutoMate/SmallTalk.py", line 72, in SingleQueryinputValue
RecommendCourse.getUdacityCourse(str(val))
File "/home/sh4d0w/PycharmProjects/AutoMate/RecommendCourse.py", line 160, in getUdacityCourse
getYoutubeCourse(course_name, driver)
File "/home/sh4d0w/PycharmProjects/AutoMate/RecommendCourse.py", line 98, in getYoutubeCourse
search_bar.send_keys(course_name)
File "/home/sh4d0w/PycharmProjects/AutoMate/venv/lib/python3.7/site-packages/selenium/webdriver/remote/webelement.py", line 479, in send_keys
'value': keys_to_typing(value)})
File "/home/sh4d0w/PycharmProjects/AutoMate/venv/lib/python3.7/site-packages/selenium/webdriver/remote/webelement.py", line 633, in _execute
return self._parent.execute(command, params)
File "/home/sh4d0w/PycharmProjects/AutoMate/venv/lib/python3.7/site-packages/selenium/webdriver/remote/webdriver.py", line 321, in execute
self.error_handler.check_response(response)
File "/home/sh4d0w/PycharmProjects/AutoMate/venv/lib/python3.7/site-packages/selenium/webdriver/remote/errorhandler.py", line 242, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.ElementNotInteractableException: Message: element not interactable
(Session info: chrome=81.0.4044.129)
2020-04-29T08:00:02Z <Greenlet at 0x7fd2089c67b8: _process_message({'call': 2.1877049007713376, 'name': 'SingleQueryi, <geventwebsocket.websocket.WebSocket object at 0x7)> failed with ElementNotInteractableException
Code sample
option = webdriver.ChromeOptions()
option.add_argument("window-size=1200x600");
driver = webdriver.Chrome('/usr/bin/chromedriver', options=option)
driver.get("https://www.youtube.com")
getYoutubeCourse(course_name, driver)
getYoutubeCourse() function body
def getYoutubeCourse(course_name, driver):
time.sleep(2)
search_bar = driver.find_element_by_xpath('//*[#id="search"]')
search_bar.send_keys(course_name)
search_bar_button = WebDriverWait(driver, 5).until(EC.element_to_be_clickable(
(By.XPATH, '//*[#id="search-icon-legacy"]')))
search_bar_button.click()
......
then after this, the logic of scraping the youtube links is there
I also tried web driver wait and all, and my drivers are also up to date
Please help I am new in python and selenium
There is 3 elements found by xpath : //*[#id="search"]
You have to correct it to
//input[#id="search"]
I also got the same problem. After hours filled with agony I finally found a solution.
While copying xpath (or any another id you are using to refer it) it points out to the entire search box container. After repeated trials and observations I found that a particular element (of the webpage which you can view in developer) with input mentioned was the one to be looked for:
<input id="search" autocapitalize="none" autocomplete="off" autocorrect="off" name="search_query" tabindex="0" type="text" spellcheck="false" placeholder="Search" aria-label="Search" aria-haspopup="false" role="combobox" aria-autocomplete="list" dir="ltr" class="ytd-searchbox" style="outline: none;">
The problem while copying xpath is that you get id of the container.
So use 'copy full xpath'. This will refer to the particular element within the container which can be given input.
full xpath for the input element of search box is:
'/html/body/ytd-app/div/div/ytd-masthead/div[3]/div[2]/ytd-searchbox/form/div/div[1]/input'
You can use it like:
search_bar = driver.find_element_by_xpath('/html/body/ytd-app/div/div/ytd-masthead/div[3]/div[2]/ytd-searchbox/form/div/div[1]/input')
search_bar.send_keys(song_name)
time.sleep(1)#You can skip this.
search_bar.send_keys(Keys.ENTER)
P.S. Excuse the terminology. I am also a beginner and this is my first answer.
You can try this:
from selenium.webdriver.common.keys import Keys
def getYoutubeCourse(course_name, driver):
time.sleep(2)
search_bar = driver.find_element_by_xpath('//input[#id="search"]')
search_bar.send_keys(course_name)
time.sleep(1)
search_bar.send_keys(Keys.ENTER)
....
I'm the one who also got the same problem.
I tried full Xpath but it was still not working. And then, I plused [0] after xpath and it worked.
full xpath for the input element of search box is:
'/html/body/ytd-app/div/div/ytd-masthead/div[3]/div[2]/ytd-searchbox/form/div/div[1]/input[0]'
And this if full source code
chrome_driver = '/Users/Downloads/chromedriver'
driver = webdriver.Chrome(chrome_driver)
driver.get('https://www.youtube.com')
search_bar = driver.find_elements_by_xpath('/html/body/ytd-app/div/div/ytd-masthead/div[3]/div[2]/ytd-searchbox/form/div/div[1]/input')[0]
time.sleep(2)
search_bar.send_keys("black pink")
time.sleep(2)
search_bar.send_keys(Keys.RETURN)
Thank you
Please click on the link below to see the link "BEAUTY" on which I am clicking
1. I am using this code to click on the "Beauty" link
driver = webdriver.Chrome("C:\\Users\\gaurav\\Desktop\\chromedriver_win32\\chromedriver.exe")
driver.maximize_window()
driver.get("http://shop.davidjones.com.au")
object = driver.find_elements_by_name('topCategory')
for ea in object:
print ea.text
if ea.text == 'Beauty':
ea.click()
I am getting the following exceptions after clickin on the link succesfully , can anybody tell me why I am getting it ?
Traceback (most recent call last):
File "C:/Users/gaurav/PycharmProjects/RIP_CURL/login_raw.py", line 10, in <module>
print ea.text
File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webelement.py", line 73, in text
return self._execute(Command.GET_ELEMENT_TEXT)['value']
File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webelement.py", line 493, in _execute
return self._parent.execute(command, params)
File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 252, in execute
self.error_handler.check_response(response)
File "C:\Python27\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 194, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.StaleElementReferenceException: Message: stale element reference: element is not attached to the page document
(Session info: chrome=63.0.3239.132)
(Driver info: chromedriver=2.34.522940 (1a76f96f66e3ca7b8e57d503b4dd3bccfba87af1),platform=Windows NT 6.2.9200 x86_64)
Try this:
from selenium import webdriver
print("bot started")
#chromeOptions = webdriver.ChromeOptions()
#driver = webdriver.Chrome(chrome_options=chromeOptions)
def specific_text(text, ea):
return str(text) == ea.text
driver = webdriver.Chrome("C:\\Users\\gaurav\\Desktop\\chromedriver_win32\\chromedriver.exe")
driver.maximize_window()
driver.get("http://shop.davidjones.com.au")
object_ = driver.find_elements_by_name('topCategory')
text_headers = [str(specific_text('Beauty', ea)) for ea in object_]
#print(text_headers)
index_text = text_headers.index("True")
#print(index_text)
object_[index_text].click()
You need to take care of certain factors as follows :
You have tried to create a List by the name object. object is a reserved built-in symbol in most of the Programming Languages. So as per Best Programming Practices we shouldn't use the name object.
The line print ea.text is badly indented. You need to add indentation.
Once you invoke click() on the WebElement with text as Beauty you need to break out of the loop.
Here is your own working code with some minor tweaks :
from selenium import webdriver
driver = webdriver.Chrome(executable_path=r'C:\path\to\chromedriver.exe')
driver.maximize_window()
driver.get("http://shop.davidjones.com.au")
object1 = driver.find_elements_by_name('topCategory')
for ea in object1:
print (ea.text)
if ea.text == 'Beauty':
ea.click()
break
Console Output :
Sale
Brands
Women
Men
Shoes
Bags & Accessories
Beauty
There's an easier way to do this. You can use an XPath that will specify the category name you want to click. That way you don't have to loop, it will find the desired element in one search.
//span[#name='topCategory'][.='Beauty']
I'm assuming you will be reusing this code. In cases like this, I would create a function that takes a string parameter which would be the category name that you want to click. You feed that parameter into the XPath above and you can then click any category on the page.
I tested this and it's working.
My previous question was Selenium Python - Access next pages of search results
After successfully doing this for one keyword, i need to read these keywords line by line from a file, and keep on searching.
file1 = open("M:/Users/Cyborg/Desktop/Py/read.txt","r")
the url is http://www.nice.org.uk/
driver.switch_to_default_content()
str2 = file1.readline()
inputElement = driver.find_element_by_name("searchText")
inputElement.clear()
inputElement.send_keys(str2)
this reads the keyword to be searched from the file, then enters it in the search box.
inputElement.submit()
submits the query. It's pretty much the same as in the question I asked before, and everything works perfectly if str2 is static, that is I define str2='abc' instead of reading from file. However as soon as I try to read from file and continue searching, I get this error
File "M:\Users\Cyborg\Desktop\Py\test.py", line 22, in <module>
inputElement.submit()
.
.
.
.
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.StaleElementReferenceException: Message: 'Element not found in the cache - perhaps the page has changed since it was looked up' ;
For some reason I get this error.
Any help would be greatly appreciated!
Your issue is that after you perform inputElement.submit() once, the page is likely being refreshed, and at that point inputElement becomes stale.
I think getting a new reference for inputElement after each inputElement.submit() will clear it up:
inputElement.submit()
inputElement = driver.find_element_by_name("searchText")