简体   繁体   English

Python Selenium - 无法通过 xpath 获取元素

[英]Python Selenium - can't get elements by xpath

    <table class="wikitable" style="float: right;">
    <caption>Current UTC
    </caption>
    <tbody><tr>
    <td>**January 26, 2020 01:13:27 (UTC) –** <span class="plainlinks" id="purgelink"><span class="nowrap"><a class="external text" href="https://en.wikipedia.org/w/index.php?title=Coordinated_Universal_Time&amp;action=purge">Refresh</a></span></span>

</td></tr></tbody></table>

I just need to get the date.我只需要得到日期。 I tried:我试过:

utc = driver.find_element_by_xpath('//*[@id="mw-content-text"]/div/table[1]/tbody/tr/td/text()')

ERROR:错误:

invalid selector: The result of the xpath expression is: [object Text].无效选择器:xpath 表达式的结果是:[object Text]。 It should be an element.它应该是一个元素。

Please help.请帮忙。

Here is the fixed version of the xpath you are tying to get.这是您要获取的 xpath 的固定版本。

utc = driver.find_element_by_xpath('//*[@id="mw-content-text"]/div/table[1]/tbody/tr/td')
print(utc.text)

But above will include the text of the "Refresh" link.但上面将包括“刷新”链接的文本。 To only get the date you might try:要仅获取您可以尝试的日期:

utc = driver.find_element_by_xpath('//*[@id="mw-content-text"]/div/table[1]/tbody/tr/td')
utc_trim = utc.get_attribute('innerHTML').split('<')[0]
print(utc_trim)

To help with page load timing issues you may want to do something like below:为了帮助解决页面加载时间问题,您可能需要执行以下操作:

from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait

utc = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, '//*[@id="mw-content-text"]/div/table/tbody/tr/td')))
utc_trim = utc.get_attribute('innerHTML').split('<')[0]
print(utc_trim)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM