我的目标是能够在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()在这一点上,一切都是正确的。但是,当我尝试使用“NoSuchElementException”打印第一个定义时,我会得到一个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())发布于 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"))发布于 2021-11-17 03:09:52
选择相对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:https://stackoverflow.com/questions/69998189
复制相似问题