Reputation: 27
I was trying to exercise with selenium and I tried this:
phone = driver.find_element_by_xpath(("//table[@class='contact_info_table']/tbody/tr/td[contains(text(), r'\+[0-9]*']"))
in order to try to get the phone number that it's inside a table. The HTML of the table is the following:
<table class="contact_info_table">
<tbody>
<tr>
<th>......</th>
<td>
. . .
</td>
</tr>
<tr>
<th>......</th>
<td>
. . .
</td>
</tr>
<tr>
<th>Telefono:</th>
<td><img style="vertical-align:middle; display: inline-block; margin-right: 10px;" src="../img/flags/it.png" title="Italia">+1234567890</td>
</tr>
What I need to do is to get the 1234567 in the last tr. What am I doing wrong?
The error that I get is:
InvalidSelectorException: Message: Given xpath expression "//table[@class='contact_info_table']/tbody/tr/td[contains(text(), r'\+[0-9]*']]" is invalid: SyntaxError: The expression is not a legal expression.
Thank you.
Upvotes: 1
Views: 917
Reputation: 5909
It looks like you missed a parenthesis in part of your path -- after your regex, you have two closing ]]
, but you need a )
to replace the 2nd to last ]
in order to close up the contains
query:
//table[@class='contact_info_table']/tbody/tr/td[contains(text(), r'\+[0-9]*')]
I'm also not sure if the regex you are using is valid syntax for XPath. I think you need to use the matches()
method in the XPath -- like this:
/td[matches(text(), '\+[0-9]*']]
I replaced your contains
with matches
, and removed the preceding r
from your regex because I think your expression just needs to be '\+[0-9]*'
. Hopefully this helps a bit.
You also might not need to use regex at all to find the element you are trying to locate. Here's an alternate XPath that doesn't use regex, but still locates the element by grabbing the desired td
element as a sibling of the preceding th
:
//th[text()='Telefono:']//following-sibling::td
So, to get the phone number, you can use .text
:
phone = driver.find_element_by_xpath("//th[text()='Telefono:']//following-sibling::td").text
Upvotes: 2
Reputation: 14135
Here is the xpath that you can use.
//table[@class='contact_info_table']/tbody/tr[th[.='Telefono:']]/td
Upvotes: 0