【问题标题】:Can't find element by XPath on certain website在某些网站上无法通过 XPath 找到元素
【发布时间】:2021-11-17 02:14:52
【问题描述】:

我的目标是能够在 python 中抓取单词的定义。

首先,我试图获得“协助”一词的第一个定义,它应该是“帮助”。我正在使用 dictionary.cambridge.org

//web driver goes to page
driver.get("https://dictionary.cambridge.org/dictionary/english/assist") 

//to give time for the page to load
time.sleep(4) 

//click "accept cookies"   
driver.find_element_by_xpath("/html[@class='i-amphtml-singledoc i-amphtml-standalone']/body[@class='break default_layout amp-mode-mouse']/div[@id='onetrust-consent-sdk']/div[@id='onetrust-banner-sdk']/div[@class='ot-sdk-container']/div[@class='ot-sdk-row']/div[@id='onetrust-button-group-parent']/div[@id='onetrust-button-group']/div[@class='banner-actions-container']/button[@id='onetrust-accept-btn-handler']").click()

到目前为止,一切正常。但是,当我尝试使用“通过 xpath 查找元素”打印第一个定义时,我得到了 NoSuchElementException。我对 selenium 非常熟悉,并且之前已经抓取了数百次网页内容,但是在这个网页上,我不知道自己做错了什么。这是我正在使用的代码:

 print(driver.find_element_by_xpath("/html[@class='i-amphtml-singledoc i-amphtml-standalone']/body[@class='break default_layout amp-mode-mouse']/div[@class='cc fon']/div[@class='pr cc_pgwn']/div[@class='x lpl-10 lpr-10 lpt-10 lpb-25 lmax lp-m_l-20 lp-m_r-20']/div[@class='hfr-m ltab lp-m_l-15']/article[@id='page-content']/div[@class='page']/div[@class='pr dictionary'][1]/div[@class='link']/div[@class='pr di superentry']/div[@class='di-body']/div[@class='entry']/div[@class='entry-body']/div[@class='pr entry-body__el'][1]/div[@class='pos-body']/div[@class='pr dsense dsense-noh']/div[@class='sense-body dsense_b']/div[@class='def-block ddef_block ']/div[@class='ddef_h']/div[@class='def ddef_d db']").text())

【问题讨论】:

    标签: python selenium xpath


    【解决方案1】:

    要打印单词的抓取定义,您可以使用以下任一Locator Strategies

    • 使用xpathtext属性:

      print(driver.find_element_by_xpath("//span[contains(@class, 'epp-xref dxref')]//following::div[1]").text)
      
    • 使用xpathinnerText

      print(driver.find_element_by_xpath("//span[contains(@class, 'epp-xref dxref')]//following::div[1]").get_attribute("innerText"))
      
    • 控制台输出:

      to help:
      

    【讨论】:

      【解决方案2】:

      选择相对 xpath,而不是绝对 xpath。 You can refer this link

      尝试使用以下代码并检索数据。

      driver.get("https://dictionary.cambridge.org/dictionary/english/assist")
      
      print(driver.find_element_by_xpath("(//div[@class='ddef_h'])[1]/div").get_attribute("innerText"))
      
      to help:
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-07-05
        • 2019-11-19
        • 2021-01-13
        • 1970-01-01
        • 1970-01-01
        • 2017-07-19
        相关资源
        最近更新 更多