Python (selenium):如何在现有 html 代码中搜索新的 html 文档

Python (selenium): how to search new html document in existing html-code

我正在尝试获取有关 Amazon 的一本书的一些信息,这对我来说非常有用,直到我想 抓取 内容描述。内容描述位于 iframe 容器中,其中启动了新的 HTML 代码。 我可以通过

捕获容器
content = driver.find_element_by_xpath("//iframe[@id='bookDesc_iframe']")

但我似乎无法理解其中的内容。我试过了

content_text = content.find_element_by_xpath("//div[@id='iframeContent']")

因为这是隐藏的地方,但对我不起作用。

为了访问 iframe 内容,您需要切换到该 iframe。

driver.switch_to.frame(driver.find_element_by_xpath("//iframe[@id='bookDesc_iframe']"))

要继续使用其他元素,而不是在 iframe 中,您必须切换出 iframe,切换到默认内容,如下所示:

driver.switch_to.default_content()

添加到 @Prophet 答案中,如果您想对显式等待做同样的事情(最终会更可靠),您可以这样做:

wait = WebDriverWait(driver, 10)
wait.until(EC.frame_to_be_available_and_switch_to_it((By.XPATH, "//iframe[@id='bookDesc_iframe']")))

进口:

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC