如何从“健康”元素中提取文本

时间:2018-11-16 05:41:52

标签: python selenium selenium-webdriver xpath webdriverwait

我一直在努力寻找适合硒的正确链接以达到该游戏的HP值。

为进行自我检查,我将提供以下用户名和密码:

  

网站:https://s3-en.bitefight.gameforge.com/user/login

     

用户名:testaccount111

     

密码:python123

enter image description here

我已经尝试过health = driver.find_elements_by_xpath("//div[2]/div/div[1]/text()[5]") 但是会出错。

3 个答案:

答案 0 :(得分:2)

在xpath下使用以定位您的元素(在图像中标记)

//img[@alt='Health']/preceding-sibling::text()[1]

,但是硒不允许您使用文本节点定位元素。另一种方法是您可以使用javascript执行程序来评估xpath。

我在Java中有以下代码参考。请按照python

进行更改
JavascriptExecutor js = (JavascriptExecutor)driver;
Object health= js.executeScript("var value = document.evaluate(\"//img[@alt='Health']/preceding-sibling::text()[1]\",document, null, XPathResult.STRING_TYPE, null ); return value.stringValue;"); 
System.out.println(health.toString().trim());

OR

WebElement element = driver.findElement(By.xpath("//div[@class='gold']"));
JavascriptExecutor js = (JavascriptExecutor)driver;
String health= (String) js.executeScript("return arguments[0].childNodes[8].textContent", element);
System.out.println(health.trim());

答案 1 :(得分:1)

@NarendraR有一个很好的答案,在python中,以21500的形式获取结果的代码

health = driver.execute_script('''
  var value = document.evaluate("//img[@alt='Health']/preceding-sibling::text()[1]",document, null, XPathResult.STRING_TYPE, null );
  return value.stringValue.split('/')[0].trim().replace('.', '');
''');

以及其他方法

elem = driver.find_element_by_xpath('//div[@class="gold"]')
health = re.search(r'(\d+\.\d+)\s+/', elem.text).group(1)
health = int(health.replace('.', ''))

答案 2 :(得分:1)

根据网站https://s3-en.bitefight.gameforge.com/user/login Health 元素(即 8.460 / 21.500 )中提取文本,您需要引入 WebDriverWait 所需的可见元素,您可以使用以下解决方案:

  • 代码块:

    from selenium import webdriver
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    
    options = webdriver.ChromeOptions() 
    options.add_argument("start-maximized")
    options.add_argument('disable-infobars')
    driver = webdriver.Chrome(chrome_options=options, executable_path=r'C:\Utility\BrowserDrivers\chromedriver.exe')
    driver.get("https://s3-en.bitefight.gameforge.com/user/login")
    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//input[@class='input' and @name='user']"))).send_keys("testaccount111")
    driver.find_element_by_xpath("//input[@class='input' and @name='pass']").send_keys("python123")
    driver.find_element_by_xpath("//input[@class='btn-small' and @value='Login']").click()
    WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.XPATH, "//div[@class='gold']//img[contains(@src,'/img/symbols')]")))
    health_text = driver.find_element_by_xpath("//div[@class='gold']").get_attribute("textContent").splitlines()[5]
    print(health_text)
    
  • 控制台输出:

          8.460 / 21.500