Does using selenium change the token of the session? - selenium

i am writing a tool to check mac address online with selenium i managed to find the input and the submit but when i ask for the results it print the session id and the token
import selenium
## set up options
options = Options()
options.headless=True
browser.Firefox(options, exceutable_path=r"geckodriver_path")
browser.get("site-URL")
## mac address sent to site
elem = browser.find_element_by_id('result')
elemnt = browser.find_element_by_css_selector('#results-log')
print (elem)
print (elemnt)
the output is some session info
<selenium.webdriver.remote.webelement.WebElement (session="289e304328d8a7900f7003d4ed6530be", element="f807a2e7-8895-4e8d-b7af-ce3d27fbf897")>
i need to get the result that is on the site

You saw it right.
The variable elem is a WebElement identified through browser.find_element_by_id('result')
The variable elemnt is a WebElement identified through browser.find_element_by_css_selector('#results-log')
Printing the element will be in the following format:
<selenium.webdriver.remote.webelement.WebElement (session="289e304328d8a7900f7003d4ed6530be", element="f807a2e7-8895-4e8d-b7af-ce3d27fbf897")>
You can find a relevant discussion in Are element IDs numbers in Webdrivers?

Related

Selenium creating bulk email addresses

I want to use selenium to create several email addresses at once. I suppose they can be random but I already have a list of the email account names I want to create.
I know how to create 1 email using webdriver but how would I go about it if I want to sign up several, one after the other automatically, without having to always change the code?
Simple code for creating 1 email:
from selenium import webdriver
import time
url = 'https://hotmail.com/'
driver = webdriver.Chrome('/C:Users/Desktop/chromedriver')
driver.get(url)
driver.find_element_by_xpath("//a[contains(#class, 'linkButtonSigninHeader')]/#href").click()
time.sleep(2)
driver.find_element_by_id('MemberName').send_keys('usernameexample')
time.sleep(1)
driver.find_element_by_id('iSignupAction).click()
time.sleet(2)
driver.find_element_by_id('PasswordInput').send_keys('Passwordexample1')
time.sleep(1)
driver.find_element_by_id('iSignupAction').click()
time.sleep(2)
driver.find_element_by_id('FirstName').send_keys('john')
time.sleep(1)
driver.find_element_by_id('LastName').send_keys('wayne')
time.sleep(1)
driver.find_element_by_id('iSignupAction').click()
As others have pointed out, you could iterate over a data collection, such as an array:
array_of_usernames = ['username_one', 'username_two']
array_of_usernames.each do |username|
url = 'https://hotmail.com/'
driver = webdriver.Chrome('/C:Users/Desktop/chromedriver')
driver.get(url)
driver.find_element_by_xpath("//a[contains(#class, 'linkButtonSigninHeader')]/#href").click()
driver.find_element_by_id('MemberName').send_keys("#{username}") #INTERPOLATED BLOCK-LOCAL VARIABLE HERE
driver.find_element_by_id('iSignupAction).click()
driver.find_element_by_id('PasswordInput').send_keys('Passwordexample1')
driver.find_element_by_id('iSignupAction').click()
driver.find_element_by_id('FirstName').send_keys('john')
driver.find_element_by_id('LastName').send_keys('wayne')
driver.find_element_by_id('iSignupAction').click()
# some step to log out so that next username can register
end
If you aren't familiar with arrays or iteration, then I'd suggest looking at the docs to get your head around it: https://ruby-doc.org/core-2.6.1/Array.html#method-i-each

Selenium - Unable to find element with xpath

I am trying to find an element on this page. Specifically the bid price in the first row: 196.20p.
I am using selenium and this is my code:
from selenium import webdriver
driver = webdriver.PhantomJS()
address = 'https://www.trustnet.com/factsheets/o/g6ia/ishares-global-property-securities-equity-index-uk'
xpath = '//*[#id="factsheet-tabs"]/fund-tabs/div/div/fund-tab[3]/div/unit-details/div/div/unit-information/div/table[2]/tbody/tr[3]/td[2]'
price = driver.find_element_by_xpath(asset['xpath'])
print price.text
driver.close()
When executed I receive the following error
NoSuchElementException: Message: {"errorMessage":"Unable to find element with xpath '//*[#id=\"factsheet-tabs\"]/fund-tabs/div/div/fund-tab[3]/div/unit-details/div/div/unit-information/div/table[2]/tbody/tr[3]/td[2]'","request":{"headers":{"Accept":"application/json","Accept-Encoding":"identity","Connection":"close","Content-Length":"214","Content-Type":"application/json;charset=UTF-8","Host":"127.0.0.1:62727","User-Agent":"Python http auth"},"httpVersion":"1.1","method":"POST","post":"{\"using\": \"xpath\", \"sessionId\": \"8faaff70-af12-11e7-a17c-416247c75eb6\", \"value\": \"//*[#id=\\\"factsheet-tabs\\\"]/fund-tabs/div/div/fund-tab[3]/div/unit-details/div/div/unit-information/div/table[2]/tbody/tr[3]/td[2]\"}","url":"/element","urlParsed":{"anchor":"","query":"","file":"element","directory":"/","path":"/element","relative":"/element","port":"","host":"","password":"","user":"","userInfo":"","authority":"","protocol":"","source":"/element","queryKey":{},"chunks":["element"]},"urlOriginal":"/session/8faaff70-af12-11e7-a17c-416247c75eb6/element"}}
Screenshot: available via screen
I have used the same approach, but with different xpath, on yahoo finance and it works fine, but unfortunately the price I am looking for is not available there.
If I didn't fail to understand your requirement then this is the price you wanted to scrape. I used css selector here.
from selenium import webdriver
driver = webdriver.Chrome()
driver.get('https://www.trustnet.com/factsheets/o/g6ia/ishares-global-property-securities-equity-index-uk')
price = driver.find_element_by_css_selector('[ng-if^="$ctrl.priceInformation.Mid"] td:nth-child(2)').text
print(price.split(" ")[0])
driver.quit()
Result:
196.20p/196.60p
If you wanna stick to xpath then try this:
price = driver.find_element_by_xpath('//*[contains(#ng-if,"$ctrl.priceInformation.Mid")]//td[2]').text

Selenium unable to locate element

I have tried all the suggestions on stackoverflow but none seems to work. My code works for all other tested log in site but "https://internet-banking.dbs.com.sg/", which is the site I'm trying to write a script to log in and check my bank balance upon request.
My code is as follow:
def page_is_loaded(driver):
return driver.find_element_by_tag_name("body") != None
driver = webdriver.Firefox()
driver.get("https://internet-banking.dbs.com.sg/")
wait = ui.WebDriverWait(driver, 10)
wait.until(page_is_loaded)
print(driver.page_source)
email_field = driver.find_element_by_id("UID")
email_field.send_keys(*UID*)
password_field = driver.find_element_by_id("PIN")
password_field.send_keys(*PIN*)
password_field.send_keys(Keys.RETURN)
When I run this, I am returned selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element:...
Also, if I check driver.page_source, the result is that of the page.
I'm assuming the line that returns the body tag is the one that is failing. It's because the page hasn't loaded yet so it throws an exception. You should use Expected Conditions, specifically visibility_of_element_located and wait for the UID instead of body.

Selenium's WebDriver.execute_script() returns 'None'

My program is having trouble getting an existing class from a webpage using Selenium. It seems that my WebDriver.execute_script function is not working.
import urllib
from selenium import webdriver
#Path to the chromedriver is definitely working fine.
path_to_chromedriver = 'C:\Users\Ben\Desktop\Coding\FreeFoodFinder\chromedriver.exe'
browser = webdriver.Chrome(executable_path = path_to_chromedriver)
url = 'http://www.maidservicetexas.com/'
browser.implicitly_wait(30)
browser.get(url)
content = browser.execute_script("document.getElementsByClassName('content')");
#Just printing the first character of the returned content's toString for now. Don't want the whole thing yet.
#Only ever prints 'N', the first letter of 'None'...so obviously it isn't finding the jsgenerated content even after waiting.
print content
My program returns 'None,' which tells me that the javascript function is not returning a value/being executed. Chrome's web dev tools tell me that 'content' is certainly a valid class name. The webpage isn't even dynamically generated (my eventual goal is to scrape dynamic content, which is why I make my WebDriver wait for 30 seconds before running the script.)
Return the value:
content = browser.execute_script("return document.getElementsByClassName('content');");

Check if login was successful with Selenium

I'm just getting to grips with Selenium, and have made a simple log in script using the Firefox IDE.
What want to do now is check if the log in was successful.
The simplest way I could think of was to search for a piece of text that is only visible after log in i.e. Hi, [account name].
But I'm a little unsure on how to do this with Selenium.
Is there a way you can search for a term on a page and then act, upon its presence?
Also, is this the best way to check if your logged in?
1) Yes, I am checking for sucessful login by the way that I search for specific label. In my case that label contains ID of logged in user. Example:
<span id="username">PAVEL007</span>
So, when I log in:
driver.get("http://PAVEL007:OmgTooSecretToTellYou!#my-test-site.com");
Then I search for that label
WebElement loggedInUser = driver.findElement(By.id("username"));
And verify that I am in:
Assert.assertEquals(loggedInUser.getText(),"PAVEL007");
In nutshell:
If your website shows some specific text visible only after sucessful login, use that text
Best way is not to search for that text itself, but for element containing the text
NOTE
The driver variable is assumed healthy, living instance of WebDriver
My pseudo code is Java based
Get a url which can be accessed only after login.
url = "some url accessed only after login"
driver.navigate_to url
driver.current_url == url ? "logged_in" : "not_logged_in"
if not logged in it will be redirected to some other url. This is applicable in websites where url is not created dynamically
If you're using the IDE it should be a simple case of recording your login action and then where you have your Hi [username] element, right-click on it and then in the context menu you should see additional options that are from the IDE.
One of those should be verify text or assert text. Select that, when you then run your test case it will complete the login account and verify/assert that the Hi [username] text is on the page.
If you are using selenium IDE, it should very easy case, first of all you have to recording your login action and after login you have Hi [username] text is present on the screen, right-click on that text then select verifytext in the the context menu you should see additional options that are from the IDE.
One of those should be verify text or assert text. Select that, when you then run your test case it will complete the login account and verify/assert that the Hi [username] text is on the page
open | www.gmail.com
type | id=username |usrename
type | id=password |password
Verifytext | HI[Username]|
The obvious answer is the fluent method:
driver.getSource().contains("a string");
Personally, I prefer using cssLocator to locate values:
if ( driver.findElement(myElement).getText().equalsIgnoreCase("my value") ) //do
Verify successful login through assertion. This is my code you can verify
WebElement useremail = driver.findElement(By.xpath("//input[#placeholder='Email']"));
WebElement password = driver.findElement(By.xpath("//input[#placeholder='Password']"));
WebElement login = driver.findElement(By.xpath("//a[#class='btn-signin']"));
useremail.sendKeys("abc#mailinator.com"); password.sendKeys("XXX");
login.click(); String actualurl="url";
String expectedurl= driver.getCurrentUrl();
Assert.assertEquals(expectedurl,actualurl);
You can use WebDriverWait of selenium.webdriver.support.ui to wait for login.
from selenium import webdriver
from selenium.webdriver.support import ui
wait = ui.WebDriverWait(driver, 60)
wait.until(lambda driver: driver.find_elements_by_tag_name('fieldset')) # there is also a until_not do the not condition
# do something after the login, if not login after 60 there will throw timeout exception