【问题标题】:Python, Selenium and Chrome - How do can I detect the end of a page with dynamically generated content?Python、Selenium 和 Chrome - 如何检测具有动态生成内容的页面结尾?
【发布时间】:2021-05-02 15:08:30
【问题描述】:

我已经解决了类似性质的现有问题和谷歌搜索结果,在我目前正在抓取的特定网站中,提出的每个解决方案都不适用于我。

https://dutchie.com/embedded-menu/revolutionary-clinics-somerville/menu

我正在向 body 元素发送向下翻页键,该元素会加载要抓取的每个项目。我有两个问题,首先我无法检测到滚动何时停止。其次,我必须在浏览器窗口打开时手动单击它以允许发送密钥。我不知道如何通过代码模仿同样的焦点给予行为。

elem = driver.find_element_by_tag_name("body")
elem.send_keys(Keys.PAGE_DOWN)

我在许多不同的迭代中尝试了以下方法,无论我在页面下方多远,或者我是否使用了 innerHeight 或 body 而不是 documentElement,打印的数字都不会收费。

height = driver.execute_script("return document.documentElement.scrollHeight")

如果我尝试使用类似的方法向下滚动页面,该页面不会移动。

driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")

我不确定这是否与 iframe 有关,或者我只是误解了最佳方法。

仍然无法找到可靠检测页面结尾的方法。

谢谢!

【问题讨论】:

    标签: python selenium web-scraping


    【解决方案1】:

    导入所需的导入后

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

    当以下元素可见时,您可以验证是否已到达页面按钮:

    element = WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.XPATH, "//p[contains(text(),'License')]"))
    

    关于第二个问题,请尝试使用 Selenium 单击以下元素:

    driver.find_element_by_id("products-container").click
    

    我没有调试这个的环境,但我想这会工作

    【讨论】:

    • 对于第二个问题,我收到此错误消息。 AttributeError: 'WebDriver' object has no attribute 'find_element_by_tag_id'我稍作修改以尝试使用 css 选择器,它给了我:AttributeError: 'list' object has no attribute 'click'
    • 当然,这是我的错字。应该是find_element_by_id。对不起
    • 使用更新的代码,错误消息消失了,但页面仍然不会滚动,除非我在加载时手动点击浏览器。
    • 那奇怪....我的电脑上现在完全没有 python 来调试它,但这听起来很奇怪
    • 我会继续插话的,您能否澄清一下您的评论中关于查找页面底部的第一部分?我应该在源代码的哪个位置看到许可证?
    猜你喜欢
    • 2023-03-13
    • 1970-01-01
    • 1970-01-01
    • 2022-11-03
    • 1970-01-01
    • 1970-01-01
    • 2019-08-09
    • 2010-11-07
    • 2017-12-19
    相关资源
    最近更新 更多