selenium get element class and text - selenium

I can't find test1,test2... from the folowing html page:
<dd class="class subclass">
test1, test2, test3
</dd>
tried
//dd[contains(#class = 'class subclass') and contains(text(), 'test1')
I guess the problem in space? Or in dd tag?
PS getting error
ERROR: Invalid xpath [2]: //dd[contains(#class, "class subclass") and text() = test1]

Try
//dd[contains(text(),"test1")]

Related

Searching for n-th child in n-th parent

There is a strange behaviour when it comes to finding elements by xpath. The situation:
<body>
...
<div class="ingredients-group">
<div class="group-header">
<h3>Title 1</h3>
... other stuff
</div>
</div>
<div class="ingredients-group">
<div class="group-header">
<h3>Title 2</h3>
... other stuff
</div>
</div>
...
I want to check the text of the H3 tag on the second ingredient-group. So I did the following in Selenium:
WebElement group2 = driver.findElement(By.xpath("//div[#class='ingredients-group'][2]"));
WebElement title2 = group2.findElement(By.xpath("//h3"));
String titleText = title2.GetText();
The last statement returns "Title 1". I would expect it to return "Title 2".
Strangely, this statement returns "Title 2":
String titleText = driver.findElement(By.xpath("//div[#class='ingredients-group'][2]//h3")).getText();
I would like to use the first option (group2.findElement), because there are several other elements in the containers I would like to refer to without having to write the full xpath.
Any ideas on this?
Thanks
Use findElements to return a list of webelements (h3 tags) and then access them as you would any other list:
WebElement groups = driver.findElements(By.xpath("//div[#class='ingredients-group'][2]"));
WebElement theH3Tag = groups[0].findElement(By.xpath(".//h3")); //make this a relative xpath
String titleText = theH3Tag.GetText();
WebElement the2ndH3Tag = groups[1].findElement(By.xpath(".//h3")); //make this a relative xpath
String titleText = the2ndH3Tag.GetText();
Or loop through the list:
WebElement[] groups = driver.findElements(By.xpath("//div[#class='ingredients-group'][2]"));
for (WebElement group : groups) {
WebElement h3Tag = group.findElement(By.xpath(".//h3")); //make this a relative xpath
String titleText = h3Tag.GetText();
}

compare the 'class' of container tag

Let's say I extract some classes from some HTML:
p_standards = soup.find_all("p",attrs={'class':re.compile(r"Standard|P3")})
for p_standard in p_standards:
print(p_standard)
And the output looks like this:
<p class="P3">a</p>
<p class="Standard">b</p>
<p class="P3">c</p>
<p class="Standard">d</p>
And let's say I only wanted to print the text inside the P3 classes so that the output looks like:
a
c
I thought this code below would work, but it didn't. How can I compare the class name of the container tag to some value?
p_standards = soup.find_all("p",attrs={'class':re.compile(r"Standard|P3")})
for p_standard in p_standards:
if p_standard.get("class") == "P3":
print(p_standard.get_text())
I'm aware that in my first line, I could have simply done r"P3" instead of r"Standard|P3", but this is only a small fraction of the actual code (not the full story), and I need to leave that first line as it is.
Note: doing something like .find("p", class_ = "P3") only works for descendants, not for the container tag.
OK, so after playing around with the code, it turns out that
p_standard.get("class")[0] == "P3"
works. (I was missing the [0])
So this code works:
p_standards = soup.find_all("p",attrs={'class':re.compile(r"Standard|P3")})
for p_standard in p_standards:
if p_standard.get("class")[0] == "P3":
print(p_standard.get_text())
I think the following is more efficient. Use select and CSS Or syntax to gather list based on either class.
from bs4 import BeautifulSoup as bs
html = '''
<html>
<head></head>
<body>
<p class="P3">a</p>
<p class="Standard">b</p>
<p class="P3">c</p>
<p class="Standard">d</p>
</body>
</html>
'''
soup = bs(html, 'lxml')
p_standards = soup.select('.Standard,.P3')
for p_standard in p_standards:
if 'P3' in p_standard['class']:
print(item.text)

selenium ide extract text from input tag [value attribute]

I am using selenium IDE for writing test case and I am trying to extract content in value attribute of below tag
<div id="inputcontainer_f-5" class="FGIC" style="max-width:none;"><input type="text" autocomplete="off" name="f-5" id="f-5" class="dummyclass FastEvtFieldFocus" value="TEXT_I_WANT_TO_GET" readonly="readonly" spellcheck="true" tabindex="-1" style="">
</div>
My selenium IDE code
comment | Target | value
store text | xpath=//input[#id='f-3'] | EXTRATCED_CONTENT
echo | ${EXTRATCED_CONTENT}
Result : I am getting empty string
echo : ""
If i try to change the xpath as xpath=//input[#id='f-3']/#value I am getting following error
storeText on xpath=//input[#id='f-5']/#value with value EXTRATCED_CONTENT Failed:
The result of the xpath expression "//input[#id='f-5']/#value" is: [object Attr]. It should be an element.
How do i extract and store TEXT_I_WANT_TO_GET in variable EXTRATCED_CONTENT and echo it
Thanks
Jk
Try this below.
//input[#id='f-3']#value

Issue parsing variable from HTML with bs4

Im trying to parse the "value" of variable ( __VIEWSTATEGENERATOR ), here's the HTML code ::
<div>
<input id="__VIEWSTATEGENERATOR" name="__VIEWSTATEGENERATOR" type="hidden" value="1434571F"/>
</div>
Here's the code I am attempting to do that with ::
viewstategenerator = soup.findAll("input", {"type": "hidden", "name": "__VIEWSTATEGENERATOR"})
I then execute:: print(viewstategenerator), and I get the following string for my variable:
>>> print(viewstategenerator)
[<input id="__VIEWSTATEGENERATOR" name="__VIEWSTATEGENERATOR" type="hidden" value="1434571F"/>]
I was expecting to grab just the value of "1434571F", not sure why that is... Any help would be highly appreciated!!
It looks like you're close but just a tad confused about the BeautifulSoup API.
soup.findAll returns a list of all of the DOM elements that match the query you gave it. Seeing as only one element on the page can match your query, you should use soup.find instead. To get the value of the value attribute of your input element, use ['value'].
from bs4 import BeautifulSoup as Soup
html = """
<div>
<input id="__VIEWSTATEGENERATOR" name="__VIEWSTATEGENERATOR" type="hidden" value="1434571F"/>
</div>
"""
soup = Soup(html, 'lxml') # Use whatever parser you're already using.
viewstategenerator = soup.find("input", {"type": "hidden", "name": "__VIEWSTATEGENERATOR"})
print(viewstategenerator['value'])
# Prints 1434571F

how to click on text field "Quantity" which id value is changing in different scenario

<div id="div_12_1_1_1_3_1_2_1_1_1_2" class="Quantity CoachView CoachView_show" data-eventid="" data-viewid="qty" data-config="config12" data-bindingtype="Decimal" data-binding="local.priceBreak.quantity" data-type="com.ibm.bpm.coach.Snapshot_a30ea40f_cb24_4729_a02e_25dc8e12dcab.Quantity">
<div class="w-decimal w-group clearfix">
<div class="p-label-container span4">
<div class="p-fields-container controls-row span8 l-input fixed-units">
<input id="div_12_1_1_1_3_1_2_1_1_1_2-in" class="p-field span8" type="text" maxlength="16">
<input id="div_12_1_1_1_3_1_2_1_1_1_2-iu" class="p-unit span4" type="text" maxlength="2" style="display: none;">
<select class="p-unit span4" style="display: none;"></select>
<div class="p-unit span4">CM</div>
<div class="p-help-block"></div>
</div>
<div class="p-fields-container span8 l-output" style="display: none;">
</div>
</div>
<div id="div_12_1_1_1_3_1_2_1_1_1_3" class="Quantity CoachView CoachView_show" data-eventid="" data-viewid="Quantity2" data-config="config73" data-bindingtype="Integer" data-binding="local.priceBreak.numberDeliveries" data-type="com.ibm.bpm.coach.Snapshot_a30ea40f_cb24_4729_a02e_25dc8e12dcab.Quantity">
here how to click on text box of whose id is "div_12_1_1_1_3_1_2_1_1_1_2-in "
but for some scenario its changing to "div_5_1_1_1_3_1_2_1_1_1_2-in "
i have tried with the following ,
driver.findElement(By.xpath("//div/input[ends-with(#id,'__1_1_1_3_1_2_1_1_1_2-in')]")).sendKeys("98989998989");
but it is not working ..
Output:
org.openqa.selenium.InvalidSelectorException: The given selector //div/input[ends-with(#id,'__1_1_1_3_1_2_1_1_1_2-in')] is either invalid or does not result in a WebElement. The following error occurred:
InvalidSelectorError: Unable to locate an element with the xpath expression //div/input[ends-with(#id,'__1_1_1_3_1_2_1_1_1_2-in')] because of the following error:
[Exception... "The expression is not a legal expression." code: "51" nsresult: "0x805b0033 (NS_ERROR_DOM_INVALID_EXPRESSION_ERR)" location: "file:///C:/Users/SUNIL~1.WAL/AppData/Local/Temp/anonymous4157273428687139624webdriver-profile/extensions/fxdriver#googlecode.com/components/driver_component.js Line: 5956"]
Command duration or timeout: 41 milliseconds
For documentation on this error, please visit: http://seleniumhq.org/exceptions/invalid_selector_exception.html
Build info: version: '2.37.0', revision: 'a7c61cb', time: '2013-10-18 17:15:02'
you can try with the following cssSelector,
driver.findElement(By.cssSelector("div.fixed-units > input[id$='in']")).sendKeys("98989998989");
If 'in' text is present always then you can use xpath. You can try //div[contains(#id, 'in')]
ends-with is an XPath 2 query, of which none of the five major actually support v2
Your options are either to use other methods as already suggested, or for an XPath 1 solution you could use:
//div/input[substring(#id, string-length(#id) - 22) = '_1_1_1_3_1_2_1_1_1_2-in']
Although it's ugly, really.
I actually used "starts-with"...but I see you have multiple that start with "div".
If your elements all stay in the same place on the page and aren't subject to change, try this out. Here's some Java code:
By by = By.xpath("(//*[starts-with(#" + attributeName + ", '" + attributeValue + "')])[" + n + "]");
In your case, it would look like this:
By by = By.xpath("(//*[starts-with(#id, 'div')])[2]");
What this will do is pick the second element that starts with "div" in the DOM.
It's a bit of a hack...but it might work out for you.