[英]Extract text from span element using selenium in python
I'm trying to extract the contact number (XXXXX-XXXXXX) from the following HTML code using Selenium webdriver's find_element_by_xpath method.我正在尝试使用 Selenium webdriver 的find_element_by_xpath方法从以下 HTML 代码中提取联系号码(XXXXX-XXXXXX)。
<div id="contact-info">
<div class="a">
<div class="b">
<table class="c">
<tr>
<td class="d">
<div class="e">Contact Info</span></div>
</td>
<td class="f">
<div></div>
</td>
</tr>
</table>
</div>
<div class="g">
<div class="h">
<table>
<tr>
<td>
<div class="i"><span class="j">Mobile</span></div>
</td>
<td class="k">
<div class="random_class_name"><span><span dir="ltr">XXXXX-XXXXXX</span></span>
</div>
</td>
</tr>
</table>
</div>
This is my code for extracting the required data-这是我提取所需数据的代码-
print(browser.find_element_by_xpath('//div[@id="contact-info"]/div[1]/div[2]/div[1]/div[2]/span[1]/span[1]').text)
But I'm thrown with an exception saying the element can't be located.但是我抛出了一个异常,说找不到该元素。 What am I possibly doing wrong here?
我在这里可能做错了什么? How can I fix this?
我怎样才能解决这个问题?
Correct your XPath with:更正您的 XPath :
print(browser.find_element_by_xpath('//span[@dir="ltr"]').text)
To get the Mobile-Number
you can take the reference of the text Mobile
and find the next sibling.要获得
Mobile-Number
,您可以参考文本Mobile
并找到下一个兄弟姐妹。
Induce WebDriverWait
() and wait for visibility_of_element_located
() and following xpath.诱导
WebDriverWait
() 并等待visibility_of_element_located
() 并跟随 xpath。
print(WebDriverWait(browser,10).until(EC.visibility_of_element_located((By.XPATH,"//td[.//div[contains(.,'Mobile')]]/following-sibling::td[1]/div"))).text)
You need to import following libraries.您需要导入以下库。
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
contactNumber = WebDriverWait(browser, 30).until(
EC.element_to_be_clickable((By.XPATH, "//div[@class='random_class_name']//span[1]//span")))
print contactNumber.text
or或者
contactNumber = WebDriverWait(browser, 30).until(
EC.element_to_be_clickable((By.XPATH, "//span[contains(text(), 'XXXXX-XXXXXX')]")))
print contactNumber.text
Note : add below imports to your solution:注意:将以下导入添加到您的解决方案中:
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
Upddated Section: Check your table is in the iframe if so then use below code to swiutch to iframe;更新部分:检查您的表是否在 iframe 中,如果是,则使用以下代码切换到 iframe;
iframe=driver.find_element_by_tag_name("iframe")
driver.switch_to.frame(iframe)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.