【问题标题】:Get text from span tag with Python and Selenium使用 Python 和 Selenium 从 span 标签中获取文本
【发布时间】:2023-03-05 22:33:01
【问题描述】:

我正在尝试使用 Python 和 Selenium 获取此元素。

<h2 class="jobTitle jobTitle-color-purple">
    <span title="Director">Director=</span>
<h2>

这是我尝试过的:

try:
    title  = job.find_element_by_xpath('.//td[@class="title"]//a').text
except:
    title = job.find_element_by_xpath('.//h2[@class="title"]//a').get_attribute(name="title")

我做错了什么?

no such element: Unable to locate element: {"method":"xpath","selector":".//h2[@class="title"]//a"}

【问题讨论】:

    标签: python selenium selenium-webdriver xpath css-selectors


    【解决方案1】:

    您使用的定位器绝对错误。
    h2 元素类属性值为jobTitle jobTitle-color-purple,而不是title
    子元素标签名称是span,而不是a
    请试试这个:

    title  = job.find_element_by_xpath('//h2[@class="jobTitle jobTitle-color-purple"]//span').text
    

    您可能需要在此之前添加等待/延迟,以便在您尝试访问该元素之前加载页面。

    【讨论】:

      【解决方案2】:

      要打印文本Director,您可以使用以下任一Locator Strategies

      • 使用css_selectorget_attribute("innerHTML")

        print(driver.find_element(By.CSS_SELECTOR, "h2.jobTitle > span[title]").get_attribute("innerHTML"))
        
      • 使用xpathtext属性:

        print(driver.find_element(By.XPATH, "//h2[contains(@class, 'jobTitle')]/span[@title]").text)
        

      理想情况下,您需要为visibility_of_element_located() 诱导WebDriverWait,您可以使用以下任一Locator Strategies

      • 使用CSS_SELECTORtext 属性:

        print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "h2.jobTitle > span[title]"))).text)
        
      • 使用XPATHget_attribute("innerHTML")

        print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//h2[contains(@class, 'jobTitle')]/span[@title]"))).get_attribute("innerHTML"))
        
      • 注意:您必须添加以下导入:

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

      您可以在How to retrieve the text of a WebElement using Selenium - Python找到相关讨论


      参考文献

      链接到有用的文档:

      【讨论】:

        猜你喜欢
        • 2018-07-01
        • 1970-01-01
        • 1970-01-01
        • 2022-11-10
        • 2021-10-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-07-26
        相关资源
        最近更新 更多