【问题标题】:How to check if a web page's content has been changed using Selenium's webdriver with Python?如何使用 Selenium 的 webdriver 和 Python 检查网页的内容是否已更改?
【发布时间】:2014-12-24 03:06:58
【问题描述】:

以 20 秒的时间间隔比较 old_page_source 和 new_page_source 对我来说是不成功的。

# using google chrome as my browser
driver = webdriver.Chrome('chromedriverfilepath')

# 5 trials to see how often page gets updated. Currently unsuccesful
for x in range(1, 5):
    # the webpage being analyzed
    driver.get("www.somewebsite.com")

    old_page_source = driver.page_source

    print time.strftime("\n\nTRIAL %d" % x + " ,first page fetched at time...." + 'Time: %H:%M:%S')

    driver.get("www.somewebsite.com")
    new_page_source = driver.page_source

    # keep checking every 20 seconds until page is updated/changed
    while old_page_source == new_page_source:
        sleep(20)
        driver.get("www.somewebsite.com")
        new_page_source = driver.page_source

print "page was changed at time.... " + time.strftime('Time: %H:%M:%S')

【问题讨论】:

    标签: python selenium webdriver


    【解决方案1】:

    你不能依赖page_source 来做你正在做的事情。 Selenium 将报告的内容很可能是浏览器首先收到的内容。作为文档mention

    获取最后加载页面的来源。 如果页面在加载后被修改(例如,通过 Javascript),则无法保证返回的文本就是修改后的页面。请查阅正在使用的特定驱动程序的文档以确定是否返回的文本反映页面的当前状态或 Web 服务器上次发送的文本。返回的页面源是底层 DOM 的表示:不要期望它以与 Web 服务器发送的响应相同的方式进行格式化或转义。将其视为艺术家的印象。

    (强调我的。该文档用于 Java 绑定,但行为不是由 Java 绑定决定的,而是由位于浏览器端的 Selenium 部分决定的。所以这也适用于 Python 绑定。)

    要获得页面的实际状态,您应该做的是:

    driver.execute_script("return document.documentElement.outerHTML")
    

    这将为您提供整个页面的 DOM 树的序列化。

    【讨论】:

      【解决方案2】:

      如果您只想比较文本差异,您可以从正文标签中获取文本。由于源页面在每次加载时都可能发生变化,并且永远不会进入 while 循环。 (例如基于会话的信息)

      body = driver.find_element_by_tag_name("body")
      original = body.text
      newer = original
      while original == newer:
          driver.get("www.somewebsite.com")
          body = driver.find_element_by_tag_name("body")
          newer = body.text
          time.sleep(20)
      

      【讨论】:

        猜你喜欢
        • 2023-04-10
        • 2014-09-23
        • 2012-05-04
        • 2018-03-19
        • 2013-02-22
        • 2019-05-11
        • 2011-04-08
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多