【问题标题】:How to get text from textnodes seperated by whitespace using Selenium and Python如何使用 Selenium 和 Python 从由空格分隔的文本节点获取文本
【发布时间】:2020-11-18 22:35:14
【问题描述】:

我在这个页面上:

https://fantasy.premierleague.com/statistics

当您单击播放器旁边的任何“i”图标时,会出现一个弹出窗口。然后,我想得到玩家的姓氏。这就是“检查元素”的样子(“空白”实际上出现在一个框中):

<h2 class="ElementDialog__ElementHeading-gmefnd-2 ijAScJ">
 Kevin
 whitespace
 De Bruyne

我想要做的是获取出现在空格之后的文本。我可以使用以下方法获取全文(即姓名和姓氏):

player_full_name = driver.find_element_by_xpath('//*[@class="ElementDialog__ElementHeading-gmefnd-2 ijAScJ"]').text

但是我怎样才能只获得姓氏(即出现在空格之后的内容)?请注意,对于其他玩家来说,它可能是这样的:

<h2 class="ElementDialog__ElementHeading-gmefnd-2 ijAScJ">
 Gabriel Fernando
 whitespace
 de Jesus

或者像这样:

<h2 class="ElementDialog__ElementHeading-gmefnd-2 ijAScJ">
 Dean
 whitespace
 Henderson

即拆分文本并取最后一两个元素是行不通的。

【问题讨论】:

  • 添加您的代码试验以重现案例。
  • .split 在空白字符上 - '\n' 或其他什么?元素 [-1] 应该是姓氏。
  • 为什么不在同一页面上使用以下 XPath 来获取玩家名称? //div[starts-with(@class,"ElementInTable__Name")] ?因为像Gabriel Fernando de Jesus这样的玩家缺少de
  • 非常感谢大家 - @E.Wiest:是的,这是一个解决方案,但我仍然想知道如何去做。

标签: javascript python selenium xpath css-selectors


【解决方案1】:

玩家的姓氏是其父 WebElement 中的第二个或最后一个文本节点。所以提取姓氏,例如Kevin De BruyneDe Bruyne 您可以使用以下任一Locator Strategies

  • 使用CSS_SELECTORchildNodesstrip()

    driver.get("https://fantasy.premierleague.com/statistics")
    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//table//tbody/tr/td/button"))).click()
    print( driver.execute_script('return arguments[0].lastChild.textContent;', WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "h2.ElementDialog__ElementHeading-gmefnd-2")))).strip())
    
  • 控制台输出:

    De Bruyne
    
  • 使用CSS_SELECTORchildNodessplitlines()

    driver.get("https://fantasy.premierleague.com/statistics")
    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//table//tbody/tr/td/button"))).click()
    print( driver.execute_script('return arguments[0].lastChild.textContent;', WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "h2.ElementDialog__ElementHeading-gmefnd-2")))).splitlines())
    
  • 控制台输出:

    ['De Bruyne']
    
  • 注意:您必须添加以下导入:

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

参考文献

您可以在以下位置找到一些相关的详细讨论:

【讨论】:

    猜你喜欢
    • 2020-10-20
    • 2020-10-08
    • 2021-03-05
    • 2017-12-27
    • 1970-01-01
    • 2021-01-08
    • 2022-01-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多