Get get_attribute("value") after refresh the page - python

Currently mu scenario is so:
send send_keys to a field
click in "save" button (refresh the page after click)
get get_attribute("value")after refresh the page
My code:
def fill_twitter(self):
enter_twitter = "http://" + fake.text(max_nb_chars=13) + ".com"
twitter_field = self.find_element(*ContractorsLocators.TWITTER)
twitter_field.send_keys(enter_twitter)
self.find_element(*ContractorsLocators.SAVE_BUTTON).click()
time.sleep(4)
assert twitter_field.get_attribute("value") == enter_twitter
My error:
StaleElementReferenceException: Message: stale element reference: element is not attached to the page document
How can I get the get_attribute("value")?

StaleElementReferenceException: Message: stale element reference: element is not attached to the page document
The most frequent cause of this is that page that the element was part of has been refreshed, or the user has navigated away to another page.
As you are saying page is getting refreshed when click on save button. Hence to avoid this you need to find same element (refresh element) again to getting their value as below :-
assert self.find_element(*ContractorsLocators.TWITTER).get_attribute("value") == enter_twitter

As the page got refreshed, you better save the value of the attribute before the element gets Stale.
def fill_twitter(self):
enter_twitter = "http://" + fake.text(max_nb_chars=13) + ".com"
twitter_field = self.find_element(*ContractorsLocators.TWITTER)
twitter_field.send_keys(enter_twitter)
value = twitter_field.get_attribute("value")
self.find_element(*ContractorsLocators.SAVE_BUTTON).click()
time.sleep(4)
assert value == enter_twitter

To check element is visible after page is refreshed use explicit sleep() function and after 4 seconds check that component is visible or not using WebDriverWait.
element = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.ID, "myDynamicElement"));
Visit http://selenium-python.readthedocs.io/waits.html#explicit-waits for better understanding.

Related

Pop-up saying element not interactable Selenium

There are two pop-ups: One that asks if you live in California and the second one looks like this:
Here is my code:
The second pop-up doesn't show up every time and when it doesn't the function works. When it does I get an element not interactable error and I don't know why. Here is the inspector for the second pop-up close-btn.
test_data = ['Los Angeles','San Ramon']
base_url = "https://www.hunterdouglas.com/locator"
def pop_up_one(base_url):
driver.get(base_url)
try:
submit_btn = WebDriverWait(driver,5).until(EC.element_to_be_clickable((By.CSS_SELECTOR,"[aria-label='No, I am not a California resident']")))
submit_btn.click()
time.sleep(5)
url = driver.current_url
submit_btn = WebDriverWait(driver,5).until(EC.presence_of_element_located((By.XPATH, "//*[contains(#class,'icon')]")))
print(submit_btn.text)
#submit_btn.click()
except Exception as t:
url = driver.current_url
print(t)
return url
else:
url = driver.current_url
print("second pop_up clicked")
return url
I have tried selecting by the aria-label, class_name, xpath, etc. the way I have it now shows that there is a selenium web element when I print just the element but it doesn't let me click it for some reason. Any direction appreciated. Thanks!
There are 41 elements on that page matching the //*[contains(#class,'icon')] XPath locator. At least the first element is not visible and not clickable, so when you trying to click this submit_btn element this gives element not interactable error.
In case this element is not always appearing you should use logic clicking element only in case the element appeared.
With the correct, unique locator you code can be something like this:
submit_btn = WebDriverWait(driver,5).until(EC.element_to_be_clickable((By.CSS_SELECTOR,"[aria-label='No, I am not a California resident']")))
submit_btn.click()
time.sleep(5)
url = driver.current_url
submit_btn = driver.find_elements_by_xpath('button[aria-label="Close"]')
if(submit_btn):
submit_btn[0].click()
Here I'm using find_elements_by_xpath, this returns a list of web elements. In case element was not found it will be an empty list, it is interpreted as Boolean False in Python.
In case the element is found we will click on the first element in the returned list which will obviously the desired element.
UPD
See the correct locator used here.
It can also be in XPath syntax as //button[#aria-label="Close"]

Python StaleElementReferenceException: Message: stale element reference: element is not attached to the page document

I am new in selenium And when I doing the job in for loop it gave an error. The first-time loop works well when its reach for a second time it's given below error.
elenium.common.exceptions.StaleElementReferenceException: Message: stale element reference: element is not attached to the page document
I have tried with Time.wait as well as webdriver.wait
def function(foo):
driver.get("https://truckbhada.com/PostedLoadDetails?st=Maharashtra")
token = driver.find_elements_by_xpath('//table[#class="k-selectable"]/tbody/tr/td/a')
for tr in token:
tr.click()
tr = driver.find_element_by_id("ContentPlaceHolder1_btnloaddetails")
tr.click()
print("---------")
print(driver.find_element_by_id("ContentPlaceHolder1_lblmobile").text)
print("---=====---")
driver.back()
driver.back()
Just want to work this code in every time of for loop work
its work when just first time for loop works in a second time its given error.
The click navigates to another page, which means the driver losses the previously located elements. You need to relocate them every iteration. You can use index to keep trace on your location in the list
def function(foo):
driver.get("https://truckbhada.com/PostedLoadDetails?st=Maharashtra")
token = driver.find_elements_by_xpath('//table[#class="k-selectable"]/tbody/tr/td/a')
for i in range(len(token)):
tr = driver.find_elements_by_xpath('//table[#class="k-selectable"]/tbody/tr/td/a')
tr[i].click()
tr = driver.find_element_by_id("ContentPlaceHolder1_btnloaddetails")
tr.click()
print("---------")
print(driver.find_element_by_id("ContentPlaceHolder1_lblmobile").text)
print("---=====---")
driver.back()
driver.back()

Python Selenium: stale element reference: element is not attached to the page document

My program is throwing an error message "Stale element reference: element is not attached to the page document". When I looked at the previous posts (such as Python Selenium stale element fix),, I found that I am not updating the url after calling click function. I updated the url. However, it didn't fix the issue. Could anyone point out where am I making mistake please? Here is my code:
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument("--disable-infobars")
driver = webdriver.Chrome(chrome_options=chrome_options,executable_path="path of driver here")
driver.get("https://stackoverflow.com/users/37181/alex-gaynor?tab=topactivity")
if driver.find_elements_by_xpath("//a[#class='grid--cell fc-white js-notice-close']"):
driver.find_element_by_xpath("//a[#class='grid--cell fc-white js-notice-close']").click()
inner_tabs = driver.find_elements_by_xpath("//div[#class='tabs']//a")
for inner_tab in inner_tabs:
if inner_tab.text == "answers":
inner_tab.click()
time.sleep(3)
driver.get(driver.current_url)
continue
if inner_tab.text == "questions":
inner_tab.click()
time.sleep(3)
driver.get(driver.current_url)
continue
driver.quit()
when you open new URL by clicking link or driver.get() it will create new document element so old element (inner_tab) will invalidate. to solve, first collect all URL then open in loop.
urls_to_visit = []
for inner_tab in inner_tabs:
if inner_tab.text in ["questions", "answers"]:
urls_to_visit.append(inner_tab.get_attribute("href"))
for url in urls_to_visit:
driver.get(url)
time.sleep(3)
This is one of the most frustrating errors you can get with Selenium.
I recommend to try it like this:
for tab in ['answers', 'questions']:
js = "window.tab = [...document.querySelectorAll('div.tabs > a')].filter(a => a.innerText === '" + tab + "')[0]"
driver.execute_script(js)
driver.execute_script("if(window.tab) window.tab.click()")
time.sleep(3)
print(driver.current_url)
By selecting inside of the browser context you can avoid the stale references.

Python Selenium: Element currently not visible

I have this page. I have to click on Facebook icon. Upon doing it I m getting:
selenium.common.exceptions.ElementNotVisibleException: Message: Element is not currently visible and so may not be interacted with
Code is given below:
if 'log' in html.lower():
print("not logged in")
sleep(3)
#Click on Fb button
fb_element = driver.find_element_by_xpath('//a[#tooltip="Facebook"]')
fb_element.vis
fb_element.send_keys(Keys.TAB)
There is an another element with tooltip="Facebook" on the page and this element is actually invisible. Well, there are actually 10 of them:
> $x('//a[#tooltip="Facebook"]').length
10
You can find find all elements matching your locator and filter the visible one via next() and is_displayed():
facebook_links = driver.find_elements_by_xpath('//a[#tooltip="Facebook"]')
visible_link = next(link for link in facebook_links if link.is_displayed())
visible_link.click()

Python & Selenium - unknown error: Element is not clickable at point (663, 469). Other element would receive the click:

I have this Selenium Code that should click on a size selection button.
submit_button = driver.find_element_by_class_name('pro_sku')
elementList = submit_button.find_elements_by_tag_name("a")
elementList[3].click()
It works for other pages but now on one page I get this error:
selenium.common.exceptions.WebDriverException: Message: unknown error: Element is not clickable at point (663, 469). Other element would receive the click:
I don't understand it because I can look at the browser window that Selenium opens and I normally can click on these buttons.
How can I solve this?
Someone asked for the website. Here it is: http://de.sinobiological.com/GM-CSF-CSF2-Protein-g-19491.html
You can use Xpath for element selection and then use the following method
# Click on Element
def element_click(self, xpath):
xpath = re.sub('"', "'", xpath)
browser.execute_script("""
var elements = document.evaluate("%s",
document,
null,
XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE,
null);
var im = elements.snapshotItem(0);
im.click();
""" %(xpath)
)
So if your x-path is correct and item is present on DOM then definitely it will get clicked.
Happy Coding
You can use action_chains to simulate mouse movment
actions = ActionChains(driver)
actions.move_to_element(elementList[3]).perform()
elementList[3].click()
Edit
The <a> tags are not the actual sizes. Try
sizes = driver.find_elements_by_class_name('size_defaut')
sizes[3].click()
Try below:-
driver.execute_script("arguments[0].click();", elementList[3])
Hope it will help you :)

Categories