【问题标题】:How to print the partial text from an element using Selenium and Python如何使用 Selenium 和 Python 从元素中打印部分文本
【发布时间】:2020-10-06 01:44:36
【问题描述】:

我正在尝试从描述选项卡下的http://www.ktown4u.com/iteminfo?grp_no=231307&goods_no=44363#dt_wrap01 获取文本“Album Vol.1 [Every letter I sent you] LP (Normal Edition)”,但我不断收到此错误消息。

selenium.common.exceptions.NoSuchElementException:
Message: no such element: Unable to locate element: 
{"method":"xpath","selector":".//div[@class='view_body']/div[2]/span"}

不同的变体给我类似的错误信息。

driver.find_element_by_css_selector('.view_body>div:nth-child(2)>span')
driver.find_element_by_xpath(".//div[@class='view_body']/div[2]/span")
driver.find_element_by_tag_name('span')

我也试过driver.implicitly_wait(10),但无济于事。

【问题讨论】:

    标签: python selenium xpath css-selectors webdriverwait


    【解决方案1】:

    有了这个 xpath:

    '//div[@id="contents"]/div/div/div[2]/span'
    

    在开发工具中测试:

    $x('//div[@id="contents"]/div/div/div[2]/span')[0].textContent
    "Album Vol.1 [Every letter I sent you] LP (Normal Edition)"
    

    【讨论】:

    • 终端给我 - selenium.common.exceptions.NoSuchElementException: 消息:没有这样的元素:无法找到元素:{"method":"xpath","selector":"//div[@ id="contents"]/div/div/div[2]/span"}
    • 哪个驱动程序?使用 firefox 和勇敢(铬)浏览器测试正常
    • 我正在使用 chromedriver
    【解决方案2】:

    要打印文本Album Vol.1 [Every letter I sent you] LP (Normal Edition),您必须为WebDriverWait 诱导visibility_of_element_located(),您可以使用关注Locator Strategies

    • 使用CSS_SELECTOR

      driver.get('http://www.ktown4u.com/iteminfo?grp_no=231307&goods_no=44363#dt_wrap03')
      print(re.split('[*\-]',WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "div.payment-order-list>ul>li"))).text)[1])
      
    • 使用XPATH

      driver.get('http://www.ktown4u.com/iteminfo?grp_no=231307&goods_no=44363#dt_wrap03')
      print(re.split('[*\-]',WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.XPATH, "//div[@class='payment-order-list']/ul/li"))).text)[1])
      
    • 控制台输出:

      Album Vol.1 [Every letter I sent you] LP (Normal Edition)
      
    • 注意:您必须添加以下导入:

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

    【讨论】:

    • 终端给我 - selenium.common.exceptions.TimeoutException
    • 查看更新的答案并让我知道状态。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-03
    • 2020-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多