在某些网站上无法通过 XPath 找到元素

Can't find element by XPath on certain website

我的目标是能够抓取 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())

选择相对 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:

要打印单词的临时定义,您可以使用以下任一方法 :

  • 使用 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: