open 'href' variable in a new tab - python

I'm using selenium and chrome webdriver with python.
I'm trying to store 'href' inside a variable ('link' for this example) and open it in a new tab.
i know how to open a dedicated website in a new tab using this way:
driver.execute_script("window.open('http://www.example.com', 'newtab')")
but using windows.open script accepts only direct text(as far as i know) and not variables.
Here is the code:
link = driver.find_element_by_class_name('asset-content').find_element_by_xpath(".//a[#class='mr-2']").get_attribute("href") #assigning 'href' into link variable. works great.
driver.execute_script("window.open(link, 'newtab')") #trying to open 'link' in a new tab
The error:
unknown error: link is not defined
Any other way i can open 'link' variable in a new tab?

You passing on a string to execute_script, so pass not a 'link' literally, but the value from the link (concatenate):
driver.execute_script("window.open('"+link+"','icoTab');")
Another way to open a tab is sending CTRL+T to the browser:
driver.find_element_by_tag_name('body').send_keys(Keys.COMMAND + 't')
driver.get(link)
As mentioned, you can find more here 28431765/open-web-in-new-tab-selenium-python

Passing the parameter in scripts is not treating as url to make it url try This one. It works for me.
driver.execute_script("window.open('{},_blank');".format(link))
Please let me know if this work.

Related

Selenium take element screenshot - Google Chrome

I'm trying to take screenshot of a <canvas> tag element from google chrome using selenium web driver and python.
I tried using the below code,
driver.find_element_by_css('#canvas-xyz').save_screenshot('canvas.png')
It returned
AttributeError: 'WebElement' object has no attribute 'save_screenshot'
I also tried this in dev tools,
document.querySelector('#canvas-xyz').toDataURL()
It returned the following DATA URI, which is empty.
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABq8AAAAhCAYAAABHnTGeAAAEQ0lEQVR4Xu3ZMREAAAwCseLfdG38kCrgUjZ2jgABAgQIECBAgAABAgQIECBAgAABAgQIECBAgEBEYJEcYhAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBA445USECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIZASMV5lXCEKAAAECBAgQIECAAAECBAgQIECAAAECBAgQIGC80gECBAgQIECAAAECBAgQIECAAAECBAgQIECAAIGMgPEq8wpBCBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIEjFc6QIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgkBEwXmVeIQgBAgQIECBAgAABAgQIECBAgAABAgQIECBAgIDxSgcIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQyAsarzCsEIUCAAAECBAgQIECAAAECBAgQIECAAAECBAgQMF7pAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAQEbAeJV5hSAECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQLGKx0gQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBDICBivMq8QhAABAgQIECBAgAABAgQIECBAgAABAgQIECBAwHilAwQIECBAgAABAgQIECBAgAABAgQIECBAgAABAhkB41XmFYIQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgYr3SAAAECBAgQIECAAAECBAgQIECAAAECBAgQIEAgI2C8yrxCEAIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAeOVDhAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECGQEjFeZVwhCgAABAgQIECBAgAABAgQIECBAgAABAgQIECBgvNIBAgQIECBAgAABAgQIECBAgAABAgQIECBAgACBjIDxKvMKQQgQIECAAAECBAgQIECAAAECBAgQIECAAAECBIxXOkCAAAECBAgQIECAAAECBAgQIECAAAECBAgQIJARMF5lXiEIAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQICA8UoHCBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIEMgLGq8wrBCFAgAABAgQIECBAgAABAgQIECBAgAABAgQIEDBe6QABAgQIECBAgAABAgQIECBAgAABAgQIECBAgEBGwHiVeYUgBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECxisdIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQyAgYrzKvEIQAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQMB4pQMECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIZAeNV5hWCECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIGK90gAABAgQIECBAgAABAgQIECBAgAABAgQIECBAICPwDiwAIhIPZYcAAAAASUVORK5CYII=
Is it possible to take screenshot of an element using chromedriver and selenium in python. I am aware that chrome dev tools allows us to take screenshot of a particular element. Even if it is a JavaScript method also i can get the data URI using driver.execute_script() command.
WebElement doesn't have save_screenshot. You can use screenshot_as_png (property) and save it
element = driver.find_element_by_css('#canvas-xyz')
scrrenshot = element.screenshot_as_png
with open('canvas.png', 'wb') as f:
f.write(scrrenshot)
Use WebElement.screenshot()method:
def screenshot(self, filename):
"""
Saves a screenshot of the current element to a PNG image file. Returns
False if there is any IOError, else returns True. Use full paths in
your filename.
:Args:
- filename: The full path you wish to save your screenshot to. This
should end with a `.png` extension.
:Usage:
element.screenshot('/Screenshots/foo.png')
"""
So, in your example, that would be:
driver.find_element_by_css('#canvas-xyz').screenshot('canvas.png')

How to use JavascriptExecutor instead of send_keys in Python selenium

I have written a script in python using send_key to type some text in a textarea on this webpage. However, it is really slow to use send_key as my text is really chunky.
from selenium import webdriver
text = "gckugcgaygartty"
link_url ="http://www.bioinformatics.org/sms2/translate.html"
driver = webdriver.Chrome('chromedriver', chrome_options=options)
driver.get(link_url)
driver.find_element_by_tag_name("textarea").clear()
driver.find_element_by_tag_name("textarea").send_keys("gckugcgaygartty")
I then tried to replace the send_keys with execute_script() like following but it didn't work (no errors but nothing changed on the webpage), could anyone give me some advice please?
driver.execute_script("document.getElementById('main_form').getElementsByTagName('textarea')[0].click()")
driver.execute_script("document.getElementById('main_form').getElementsByTagName('textarea')[0].setAttribute('value', 'gckugcgaygartty' )")
Modification : Changed setAttribute function with value property
Use following Code :
driver.execute_script("document.getElementsByTagName('textarea')[0].value='your_lengthy_data'")
OR
driver.execute_script("document.getElementById('main_form').getElementsByTagName('textarea')[0].value='your_lengthy_data'")

Python and selenium, is not possible to open a new tab with a URL?

I've been digging around this but no luck. So my question is: is not possible to open a new url in a new tab ? ( in this case using IE).
My scenario is, open IE, open website, log into it, do some tasks, then open a new tab with a new url in that tab. When I do that, the new url always open in the first tab, not in the new one. I looked for some solutions online but any worked and found many people with same issue. Code follows below:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
path_to_Ie = 'C:\\Python34\\IEDriver\\IEDriverServer.exe' # change path as needed
browser = webdriver.Ie(executable_path = path_to_Ie)
url = 'www.test1.com'
browser.get(url)
browser.find_element_by_xpath("//*[#id='username']").send_keys("user")
browser.find_element_by_xpath("//*[#id='password']").send_keys("pass")
browser.find_element_by_xpath("//*[#id='login-link']").click()
# some coding here
browser.find_element_by_tag_name("body").send_keys(Keys.CONTROL + 't') #open new tab
browser.find_element_by_tag_name('body').send_keys(Keys.CONTROL + Keys.TAB) # it looks like it switches to the correct tab, but anyway the browser.get will open the url in the first tab
browser.get('www.test2.com') # this link must open in this new tab -> but it doesnt.
import os
os.system("taskkill /im IEDriverServer.exe")
thank you!
browser.execute_script("window.open('www.test2.com','_blank');")
This works for Chrome, but in IE it will open new window instead of new tab. If it doesn't matter for you then you can try it

How to copy a text and store it into a variable using Selenium? Python

I want to copy a text from a website and store it into a variable so I can add it to a dictionary later. I wanted to know how do I accomplish it?
Here is my source code:
from selenium import webdriver
f = webdriver.Firefox()
f.get("http://hi.com")
g = f.find_element_by_tag_name('h1').getText()
print g
What type of text you need to copy from web page?
You need to locate webelement of text you need to capture and simply use getText() on it.
String text = driver.findElement(By.id("some id")).getText();

Changing the link in python mechanize

I am trying to write a python script that will generate the rank-list of my batch. For this I simply need to change the roll-number parameter of the link using inspect element feature in web-browser. The link(relative) looks something like:
/academic/utility/AcademicRecord.jsp?loginCode=000&loginnumber=000&loginName=name&Home=ascwebsite
I just need to change the loginCode to get the grade of my batch-mates. I am trying to use python to iterate through all the roll-numbers and generate a rank-list. I used mechanize library to open the site using python. The relevant portion of code:
br = mechanize.Browser()
br.set_handle_robots(False)
response = br.open('link_to_the_page')
I then do the necessary authentication and navigate to the appropriate page where the link to view the grades reside.
Then I find the relevant link like this:
for link in br.links(url_regex='/academic/utility/AcademicRecord.jsp?'):
Now inside this I change the url and attributes of the link appropriately.
And then I open the link using:
response=br.follow_link(link)
print response.read()
But it does not work. It opens the same link i.e. with the initial roll number. In fact I tried changing the url of the link to something very different like http://www.google.com.
link.url='http://www.google.com'
link.base_url='http://www.google.com'
It still opens the same page and not google's page.
Any help would be highly appreciated.
According to the source code, follow_link() and click_link() use link's absolute_url property that is set during the link initialization. And, you are setting only url and base_url properties.
The solution would be to change the absolute_url of a link in the loop:
BASE_URL = 'link_to_the_page'
for link in br.links(url_regex='/academic/utility/AcademicRecord.jsp?'):
modified_link = ...
link.absolute_url = mechanize.urljoin(BASE_URL, modified_link)
br.follow_link(link)
Hope that helps.

Categories

Resources