如何获取刷新的div(硒)数据

时间:2018-06-28 21:48:41

标签: python-3.x selenium selenium-chromedriver

我正在尝试抓取一个内容(divs)每2秒刷新一次的网站。

我的当前代码除了可以继续获取StaleElementReferenceException之外还可以,因为元素持续刷新所有内容2秒钟。

以下是我到目前为止所拥有的

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.chrome.options import Options


import time, sys

option = webdriver.ChromeOptions()
browser = webdriver.Chrome(executable_path='chromedriver', chrome_options=option)
browser.get("example.com")

sports_categories = browser.find_elements_by_css_selector('div.sidebar-wrapper')

for sport in sports_categories:
   if sport.text == 'FOOTBALL':
        sport.click()
        time.sleep(2)

        sub_menus_html = browser.find_element_by_css_selector('div.category.lvl1.open  div.dropdown')

        print(sub_menus_html)

我的问题是,

  • 如何处理这种情况,以便即使div在后台刷新也能获得准确的目标内容

任何帮助或建议将不胜感激。

2 个答案:

答案 0 :(得分:1)

由于您的import pymysql pymysql.install_as_MySQLdb() import MySQLdb dbconn = MySQLdb.connect("URL", "USERNAME", "PASSWORD", "DATABASE") cursor = dbconn.cursor() cursor.execute("YOUR QUERY GOES HERE") cursor.fetchall() dbconn.commit() dbconn.close() 正在刷新元素,因此您必须在 DOM 中收集当前元素,因为在开始循环之前收集的元素列表已变为 < em> STALE

下面是一个示例,说明如何循环并不断更新要循环的元素的列表对象:

click()

由于我无权访问您正在使用的网站,因此不确定此确切的代码块是否可以按原样工作。

如果option = webdriver.ChromeOptions() browser = webdriver.Chrome(executable_path='chromedriver', chrome_options=option) browser.get("example.com") sports_categories = browser.find_elements_by_css_selector('div.sidebar-wrapper') # add counter to keep track counter = 0 for sport in sports_categories: #add category refresh here current_categories= browser.find_elements_by_css_selector('div.sidebar-wrapper') if current_categories[counter].text == 'FOOTBALL': current_categories[counter].click() # I would recommend using something other than sleep to wait for load # like webdriverwait conditions combined with Expected Conditions time.sleep(2) sub_menus_html = browser.find_element_by_css_selector('div.category.lvl1.open div.dropdown') print(sub_menus_html) counter += 1 中项目的长度发生变化,或者该边栏中的项目顺序发生变化,则可能会出现问题。

但是,刷新要循环的元素列表背后的逻辑仍然成立。

答案 1 :(得分:0)

我不确定如何在Python API中执行此操作,但是在NodeJS WebDriver API中,您可以waitForVisible特定的XPath选择器,然后单击它。在您的情况下,选择器可能是:

//div[contains(@class, 'sidebar-wrapper')][text() = 'FOOTBALL']