如何使用Selenium和Python从以空格分隔的textnodes中获取文本

2024-10-03 23:27:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我在这一页:

https://fantasy.premierleague.com/statistics

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

<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

即拆分文本并提取最后一两个元素将不起作用


Tags: https文本元素玩家h2空白fantasyclass
1条回答
网友
1楼 · 发布于 2024-10-03 23:27:06

玩家的姓氏是其父节点WebElement中的第二个或最后一个文本节点。因此,从Kevin De Bruyne中提取姓氏,例如,De 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
    

参考资料

您可以在以下内容中找到一些相关的详细讨论:

相关问题 更多 >