So I'm trying to open a new window by executing a script in Selenium using driver.execute_script("window.open('');")
But I want to open a link given by the user.
So I got the link input from my array and put it to my javascript code just like this:
driver.execute_script("window.open(data[0]);")
Now It's giving an error like this:
selenium.common.exceptions.JavascriptException: Message: javascript error: data is not defined
How to fix this? Thanks for your time.
EDIT: A part of my code is something like that:
from selenium import webdriver
import PySimpleGUI as sg
import time
global data
data = []
layouts = [[[sg.Text("Enter the Wordpress New Post link: "), sg.InputText(key=0)]],
[sg.Button('Start The Process'), [sg.Button('Exit')]]]
window = sg.Window("Title", layouts)
def selenium_process():
# Getting the driver path
driver = webdriver.Chrome(r'Driver\path')
driver.get('https://google.com')
driver.execute_script(f"window.open({data[0]});")
time.sleep(10000)
while True:
event, values = window.read()
if event in (sg.WIN_CLOSED, 'Exit'):
break
data.append(values[0])
selenium_process()
did you try string interpolation ?
Try this:
driver.execute_script(f"window.open({data[0]});")
Your solution does not work since data[0] is a string, not a variable. You instead need to substitute data[0] with its value (must be a value that JS can understand).
Please read the description of Javascript window.open : https://developer.mozilla.org/fr/docs/Web/API/Window/open
If you just need to get to an URL:
driver.get(data[0])
Related
I want to extract data from a website that uses hicharts within its login area.
https://www.highcharts.com/demo/line-basic
I would like to do it without the use of selenium or phantomJS, which both would be overkill but I´m not sure how.
In selenium my code would look like this:
data = driver.execute_script('''
values = [];
Highcharts.charts[0].series[0].data.forEach((d) => values.push(d.y));
return values;
''')
If you want to test this in your browsers console use:
values = [];Highcharts.charts[0].series[0].data.forEach(function(d){ values.push(d.y) });console.log(values);
As I understand requests_html has JS support but I was not able to make any progress.
c=session.html.render(script='''values = [];
Highcharts.charts[0].series[0].data.forEach((d) => values.push(d.y));
return values;''')
This gives me an error:
AttributeError: 'HTMLSession' object has no attribute 'html'
Is there another way to achieve this goal?
Context
I am currently going through a course on webscraping. Upon getting to the module on scraping javascript, a function set_1.difference(set_2) was used to distinguish the old variables from the newly created variables. But when I did it, it brought up this error:
AttributeError: 'list' object has no attribute 'difference'
I searched online and stumbled on this website. But running the example on their own website brought up an error
Problem
Any reason why this is not working? I want to print the newly generated javascript links. Below is the code I am trying to run:
from requests_html import AsyncHTMLSession
session = AsyncHTMLSession()
r = await session.get('https://www.ons.gov.uk/economy/economicoutputandproductivity/output/datasets/economicactivityfasterindicatorsuk')
r.status_code
divs = r.html.find('div')
downloads = r.html.find('a')
urls = r.html.absolute_links
# Now need to render the javascript. Downloads chromium the first time we use it,
# It is a browser that has no GUI
await r.html.arender()
new_divs = r.html.find('div')
new_downloads = r.html.find('a')
new_urls = r.html.absolute_links
# Get only the newly created html
new_downloads.difference(downloads)
Don't know what the "r" object is, so can't verify your code but difference is a method of sets, not lists.
https://docs.python.org/3/library/stdtypes.html#frozenset.difference
This should do the trick: set(new_downloads).difference(downloads)
I am trying to use the beanshell script posted here to get the path of the jmx that is being run in my jmeter test - Access to JMeter script path
It is working and if I log the output of the path when set by beanshell or view the variables with the debugger I get the path to the script displayed as I expected -
c:\my\path\to\script
but when I then try to pass that variable into sendKeys, the slashes "\" are being removed so -
c:mypathtoscript
And this doesn't work so I am unable to attach/upload my file..
Sure I am missing something stupid
Thanks
Needed to user vars.put to put the JMeter UDV value into a Javascript variable, then use javascript concatenate to link it all together.
There are at least 2 ways to get this done without using Beanshell:
Call FileServer methods from WebDriver Sampler:
someElement.sendKeys(org.apache.jmeter.services.FileServer.getFileServer().getBaseDir())
Get the value from JMeterVariables
var vars = org.apache.jmeter.threads.JMeterContextService.getContext().getVariables()
someElement.sendKeys(vars.get('homepath'))
Example full code:
WDS.sampleResult.sampleStart()
WDS.browser.get('http://ya.ru')
var searchInput = WDS.browser.findElement(org.openqa.selenium.By.id('text'))
//directly access function from JavaScript
searchInput.sendKeys(org.apache.jmeter.services.FileServer.getFileServer().getBaseDir())
//alternative way - getting the value from JMeter Variables
var vars = org.apache.jmeter.threads.JMeterContextService.getContext().getVariables()
searchInput.sendKeys(vars.get('homepath'))
WDS.sampleResult.sampleEnd()
Comprehensive information on accessing JMeter API classes from WebDriver Sampler and few more tips and tricks: The WebDriver Sampler: Your Top 10 Questions Answered
I am working inside a jquery, getJSON callback function using flask as my web framework.
I am trying to set the link desination for a dynamically created dom element. I want to set it to the jinja2 code for url_for. So, I would like to do something like this:
a.href ="{{ url_for('write_response', id=".concat(data.libArticles[i].id.toString(), ") }}");
I have had the worst time doing this. First, it would not recognize the "{{" and "}}" strings, removing them, opening quotes and doing other weird stuff because of those characters. Finally, by doing this:
var url1 = "{url_for('write_response', id=".concat(data.libArticles[i].id.toString(),")}");
var url2 ="{".concat(url1, "}");
a.href = url2;
it finally accepted the string with two instances of "{", so it accepted "{{somethig}}"
This still did not work and instead, when the link is clicked, it redirects to the following and fails :
http://localhost:5000/write_response/%7B%7Burl_for('write_response',%20id=3)%7D%7D
Does anyone know how to do this?
Your mixing up your python and javascript. Your first attempt failed, because your trying to execute javascript inside python. What's actually happening is everything, including the ".concat is being treated as the value for your id. Your second attempt is even more confused.
It's worth remembering that the python code gets executed on the server and then sent to the browser, the javascript gets executed after the fact in the browser. So the python/jinja code can't possibly know about the value of a javascript variable.
I think you should be able to do something like the following to get it to work:
var url = "{{ url_for('write_response') }}";
var id = encodeURIComponent(data.libArticles[i].id.toString());
url += '?id='+id;
Everything inside the set of {{ }} is considered jinja code, seperate from whatever is going on around it in the file. this should translate into the following in the browser:
var url = "/write-response";
var id = encodeURIComponent(data.libArticles[i].id.toString());
url += '?id='+id;
which should get you something like /write-response?id=12345
The encodeURLComponent(..) call just makes sure the value is url safe.
this error comes up when using the following :
field otherinfo has id=idOtherInfo and is declared in a .xml file under Models, Forms in joomla.
The field has a default value in the declaration to prevent the null (shows the default value in the browser) and using the
onchange="dosomething()"
I am running a javascript file, which runs ok as it shows an alert and then it halts on the command
var first1 = document.getElementById("idOtherInfo").value;
The javascript file is loaded by
JHtml::script(JURI::root() . 'media/com_hr/js/validateFields.js', true);
also can be loaded by
$document = JFactory::getDocument();
$document->addScript(JURI::root().'media/com_hr/js/validateFields.js');
Can you please help?
Thanks
It means that element with ID idOtherInfo dosen't exist. Check your source code of web page to be sure that it shows your input correctly.
SOLUTION
If Joomla! generates forms from XML file, it adds jform_ to start of input and label ID and -lbl to end of label.
So for getting input value
var first1 = document.getElementById("jform_idOtherInfo").value;
and for label
var first1 = document.getElementById("jform_idOtherInfo-lbl").innerHTML;
This could be a long shot but I think you've had a little mix up with the name of the ID. Try changing this:
document.getElementById("idOtherInfo").value;
to this:
document.getElementById("OtherInfo").value;