首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在某些网站上无法通过XPath找到元素

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

Stack Overflow用户
提问于 2021-11-17 02:14:52
回答 2查看 131关注 0票数 1

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

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

代码语言:javascript
复制
//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()

在这一点上,一切都是正确的。但是,当我尝试使用“NoSuchElementException”打印第一个定义时,我会得到一个NoSuchElementException。我对selenium相当熟悉,以前已经刮过好几百次了,但是在这个网页上,我不知道我做错了什么。下面是我使用的代码:

代码语言:javascript
复制
 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())
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2021-11-17 09:57:06

要打印单词的刮擦定义,可以使用以下任一定位器策略

  • 使用xpath和text属性: print(driver.find_element_by_xpath("//spancontains(@class,'epp-xref dxref‘)/以下:div1 1“).text)
  • 使用xpath和innerText: print(driver.find_element_by_xpath("//spancontains(@class,'epp-xref dxref')//following::div1").get_attribute("innerText"))
  • 控制台输出: 帮助:
票数 0
EN

Stack Overflow用户

发布于 2021-11-17 03:09:52

选择相对xpath代替绝对xpath。您可以参考此链接。

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

代码语言:javascript
复制
driver.get("https://dictionary.cambridge.org/dictionary/english/assist")

print(driver.find_element_by_xpath("(//div[@class='ddef_h'])[1]/div").get_attribute("innerText"))
代码语言:javascript
复制
to help:
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69998189

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档