簡體   English   中英

在某些網站上無法通過 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。 你可以參考這個鏈接

嘗試使用以下代碼並檢索數據。

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:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM