如何从给定的锚定标记中提取标题

2024-05-05 02:55:04 发布

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

如何让xpath从这个html行中提取标题。在

没有得到任何有用的东西,因为cssClass会随着时间变化,所以代码可能会中断。我想,由于这个标记中的href和text都是我要提取的名称,所以可能使用一个相等条件。在

<a class="FPmhX notranslate nJAzx" title="ceorackz_adpp" href="/ceorackz_adpp/">ceorackz_adpp</a>

我希望python代码兼容,要么使用selenium API调用,要么使用普通regex来获取这个锚定标记的标题或文本。在


Tags: 代码text标记名称标题html时间条件
3条回答

要从元素中提取标题,即ceorackz_adpp,您必须为visibility_of_element_located()归纳WebDriverWait,并且可以使用以下任一解决方案:

  • 使用CSS_SELECTOR

    print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "a.notranslate[href='/ceorackz_adpp/']"))).get_attribute("title"))
    
  • 使用LINK_TEXT

    print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.LINK_TEXT, "ceorackz_adpp"))).get_attribute("title"))
    
  • 使用XPATH

    print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//a[contains(@class, 'notranslate') and @href='/ceorackz_adpp/']"))).get_attribute("title"))
    
  • 注意:您必须添加以下导入:

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

使用以下列表中的任何xpath:

//a[@title='ceorackz_adpp']

//a[text()='ceorackz_adpp']

//a[@title='ceorackz_adpp' and text()='ceorackz_adpp']

右键单击inspect部分中的HTML元素。 然后转到Copy > Copy XPath。 那就用这个代码

title = driver.find_element_by_xpath("copied_xpath").get_attribute("title")
href = driver.find_element_by_xpath("copied_xpath").get_attribute("href")
text = driver.find_element_by_xpath("copied_xpath").text

相关问题 更多 >