How to write an Xpath expression containing an apostrophe in VBA Selenium - excel

My question relates to coding selenium specifically in VBA.
I have a function that finds webelements based on text passed to it (in string variable 'toFind'). The relevent Xpath identification method I use is (where driver. is the selenium chromedriver):
mySearch = "//*[contains(text(),'" & toFind & "')]"
Set ret = driver.FindElementsByXPath(mySearch)
This works unless the toFind variable contains an apostrophe. For example if "Consultant's Forename" is passed then my expression evaluates to:
Set ret = driver.FindElementsByXPath("//*[contains(text(),'Consultant's Forename')]"), which causes an invalid selector run-time error.
I have researched elsewhere on the site and see a number of answers describing escaping from the single quotes using the backslash character. Based on this I have tried to use Set ret = driver.FindElementsByXPath("//*[contains(text(),\"Consultant's Forename\")]") instead. However, this will not compile in microsoft visual basic for applications as it reports a syntax error (code line is red). I have not tried using the driver.findElements(By.xpath method as opposed to driver.FindElementsByXPath as I assumed this would not make a difference to the handling of the XPath expression. I have tried the other suggestions of using the 'concat' function but this also seems not to be valid in VBA selenium.
I don't know if these methods are specficaly for platforms other than VBA or I am just getting my syntax wrong?
The only way I can work it at present is to ignore the existence of the apostrophe:
Set ret = driver.FindElementsByXPath("//*[contains(text(),'Consultant') and contains(text(),'s Forename')]")
Whilst this works it is an incomplete solution and any help on the correct syntax to deal with the xpath location in VBA for text containing an apostrophe would be much appreciated.

Related

Import from Excel via foreach loop

I intend to import and work with a variety of Excel files through a foreach loop. The import itself is not working though as Stata won´t recognize `x' as a substitute for the Excel filenames.
local excelfiles "bb_01 bit0_2 bun comp_03 comp_c01m LLU-ck"
foreach item of local excelfiles {
import excel using "D:\...\...\...\Data\Files\`x'.XLS", sheet("DynamicReport") cellrange(A2:AI201) firstrow
keep v1 v2 v3 v4
save "D:\...\...\...\...\`x'.dta", replace
The error I get is file D:\...\...\...\...\Data\Files.XLS not found
There are various problems here.
Your code is inconsistent. You declare item in the foreach statement, but refer to x within the loop. So, as far as Stata is concerned, local macro x is never defined. That is not an error in itself, but Stata replaces references to local macros that do not exist (are empty) with an empty string, with the consequence you report.
Your code would still not work if you replace reference to x with reference to item. See (e.g.) http://www.stata.com/manuals14/u.pdf 18.3.11 and http://www.stata-journal.com/sjpdf.html?articlenum=pr0042 for warnings on following backslashes immediately with local macro references. The problem is that backslash is both an escape character and a separator within full Windows filepaths. The clash should be resolved by using forward slashes in filepaths, even within Windows.
The loop is never closed in the code segment you show.
I can't check your code otherwise, as your code is not reproducible. I am presuming that the triple dots ... are not literal but replace detail that should not be crucial.

Firebug identified xpath not working in protractor

Firebug identified xpath not working in protractor.I ahve cretaed xpath using firebug.When I identify the xpath using IDE,it is working fine.However when I use the same xpath in protractor,it is not working.My element does not have id or name.So here i can use only xpath option.
Please find the below image for reference.
Here I need to verify whether that particular element has "IRCTC Attractions" text.
Could you please help me?
HTML code:
//div style="width:100%;" class="g_hedtext">IRCTC Attractions /div
Find the element by text and assert it's present:
var elm = element(by.xpath("//div[. = 'IRCTC Attractions']"));
expect(browser.isElementPresent(elm)).toBe(true);
OK, looking at your error message (in the comment):
Exception loading: SyntaxError:
C:\Users\XXXX\AppData\Roaming\npm\TC_model2.js:7
var disclaimermessage = element(by.xpath('//[#id='disclaimer-message']'));
^^^^^^^^^^ Unexpected identifier
(I'm guessing where the carets before "Unexpected identifier" were aligned. Is that right?)
The problem is that you've used single quotes both to delimit the string 'disclaimer-message', and to delimit the whole XPath expression '//[#id='disclaimer-message']'. Thus it appears to the parser that your XPath expression is the stuff between the first two single quotes: '//[#id=', and then the disclaimer-message is some other identifier without any comma or other operator to show what it's doing there.
The solution is to use double quotes inside the XPath expression. XPath accepts either single or double quotes; it doesn't care, as long as you match them with each other. So change the offending line to
var disclaimermessage = element(by.xpath('//[#id="disclaimer-message"]'));
And you should be good to go.
For future reference, this question would have been quicker and easier to answer if you had told us about the error message in the first place.

Making sure string numbers operations are culture independent

I download an exchange rate through an XmlHttp request that gets inside the code as a string (being the .innerText of a <div> element) and represents a double type number: 1.525.
When building this script, I've done it on my OS which has the English culture model (i.e. 1.525 means 1 unit and 0.525 decimals).
However, this script will now run on a French OS which uses the comma , instead of the . to separate decimals.
Which means, the operation Application.Evaluate(10000/myRate) will fail if the . is instead of the ,.
Easy solution would be to replace the "." with a "," via Application.Evaluate(10000/Replace(myRate,".",","). However, this is clearly not nice because now the script would fail on an English system.
With VB.NET I would be able to make it culture-independent by converting it like:
myRate.ToDouble(System.Globalization.CultureInfo.InvariantCulture)
I've tried Googling the VBA alternative for a while without success; does anyone know if there's a more elegant way of internationalize my script than just replacing the "." with a ","?
Here's my current solution (that I don't really like):
On Error Resume Next
test = CDbl(myRate)/2
If Err.Number <> 0 Then
myRate = Replace(myRate,".",",")
On Error GoTo 0
End If
use the Application.DecimalSeparator property?
Application.Evaluate(10000/CDbl(Replace(myRate,".", Application.DecimalSeparator))
You can temporary change decimal and thousands separator, by using Application object.
To read several current OS (International) settings: Application.International(index) property
To change:
Application.ThousandsSeparator = "."
In MS Access, we do not have Application.DecimalSeparator nor Application.ThousandsSeparator nor Application.International. The only thing we have is Val(vString) and Str(vNumber). They both convert the argument using the English (invariant) culture.
So, in MS Access the OP's question could be solved like this:
vResult = 10000/Val(myRate)

findElement By XPath not supported in Selenium VBA?

variableName = driver.findElement(By.XPath(".//*[#id='T_F2']/fieldset/div[1]/div/div[4]/span[2]"))
Running the above always seems to lead to the error:
Why is this? I always see other people using findElement By XPath. If it helps, I generated about half of my code using Selenium's 'record' feature. I then converted the code into 'VBA/Webdriver' before pasting it into Excel to use as a Macro.
What exactly is wrong with my code? I have used findElement a number of times before, so I'd have to guess that the problem is with the By.XPath part of my code... Is there any way around this?
Edit: Even variableName = driver.findElementsByXPath(".//*[#id='T_F2']/fieldset/div[1]/div/div[4]/span[2]") leads to the error 'Invalid procedure call or argument' even though it looks fine to me.
Try:
variableName = driver.findElementByXPath("//div[#id='T_F2']/fieldset/div[1]/div/div[4]/span[2]")
Notice that I removed the . in the beginning of the xPath and replaced * with div. Also, you're missing something at the end. You are just declaring the path here and not really getting a value.
EDIT: Referring to just the xPath is not usually enough. Do you want to perform an action on it, get the text inside, the tagname, etc.?
EDIT2: Testing to get the .Text attribute returns a "findElement By XPath not supported in Selenium VBA?" message.
Here's what works for me:
Dim variableName() as variant
variableName = driver.findElementsByXPath("//div[#id='T_F2']/fieldset/div[1]/div/div[4]/span[2]").getdata
Notice it's "find elements [plural] by XPath". This creates a two-dimensional array. variableName(1,1) will have the data you're looking for.
(I know it's been more than 6 years, but it's my first contribution and I can't resist! Maybe that can help someone else)
You have to initialise the following:
Dim By As New By, variableName As WebElement
and because variableName is an object, it has to be declared, as follows:
Set variableName = driver.FindElement(By.Xpath(".//*[#id='T_F2']/fieldset/div[1]/div/div[4]/span[2]"))

Coldfusion not converting accented text or MS Word chars

Running Coldfusion 8, I am trying to clean text input before saving to a database that will take things like the MS equivalent of ' " - and accented letters, and converting them.
I have tried replace, REReplace, and various UDFs found on the internet. None seem to work. In fact, I tried this:
<cfscript>
function cleanString(string) {
var newString = string;
newString = replace("'", "'", ALL);
return newString;
}
</cfscript>
The single quote to be replaced above is a MS Word style single quote. Coldfusion threw an error, the error scope said invalid syntax and the single quote in the error scope was a square. If I change it to the chr() form, and replace with ', I get a blank. If I do chr() to the entity, I get a blank.
I am more than certain I have jumped this hurdle before, and not sure why nothing is working now. Is there a new setting in CF8 vs CF7 regarding character encoding that I am missing?
There is a great script for demoronizing (yes, that's a technical term) text copied from MS word and the like. It can be found at CFLib:
http://cflib.org/index.cfm?event=page.udfbyid&udfid=725
I've used it several times, and been happy with it out-of-the-box (though I have added some additions for specific applications).

Resources