抓取不断更新的网页

2024-04-26 20:24:14 发布

您现在位置:Python中文网/ 问答频道 /正文

感谢您抽出时间来检查这个问题。你知道吗

我试图从CAISO website中搜集公开投标数据。我遇到了这些问题:

a.页面不断更新,所以我认为我的代码 卡住了。你知道吗

b.XML对象标记在每个新会话中都会更改。你知道吗

对于(a),我尝试使用时间。睡眠发送一个ESC键来停止刷新,但它不起作用。你知道吗

不过,我不知道怎么解(b)。我通常做的是使用Chrome扩展,它允许我在页面中获取XML元素,并在代码中使用这些元素来做我想做的事情。如果他们每次都改变,这个策略就不起作用了。你知道吗

我想做的是:

  1. 打开http://oasis.caiso.com/mrioasis/logon.do
  2. 单击“公开投标”>;“公开投标”
  3. 循环浏览日期列表,下载每个日期的CSV文件。你知道吗

以下是我目前的代码:

driver = webdriver.Chrome()
driver.get('http://oasis.caiso.com/mrioasis/logon.do')
PublicBids = driver.find_element(By.XPATH, '//*[@id="IMG_111854124"]')
PublicBids.click()

dates = ['04/18/2019']

def BidsScraper(d):
    time.sleep(2)
    dateField = driver.find_element(By.XPATH,'//*[@id="TB_101685670"]')
    dateField.send_keys(d)
    DownloadCSV = driver.find_element(By.XPATH, '//*[@id="BTN_101685706"]')
    DownloadCSV.click()

欢迎任何建议!再次感谢。你知道吗

编辑:格式


Tags: 代码idhttp元素bydriver时间页面
2条回答

要尝试的两件事是强制刷新停止,并且仅当元素是用Selenium找到的时候才单击,或者如果这仍然对您不起作用,我通常会尝试一些方法,比如用AppRobotic Personal之类的宏程序将鼠标移到X/Y坐标,然后模拟鼠标单击按钮的X/Y坐标。在Try/Except中与此类似的内容:

import win32com.client
x = win32com.client.Dispatch("AppRobotic.API")
from selenium import webdriver

driver = webdriver.Chrome()
driver.get('http://oasis.caiso.com/mrioasis/logon.do')
PublicBids = driver.find_element(By.XPATH, '//*[@id="IMG_111854124"]')
PublicBids.click()
dates = ['04/18/2019']

def BidsScraper(d):
    # wait for loading
    x.Wait(2000)
    # forcefully stop page reload at this point
    driver.execute_script("window.stop();")
    try:
        dateField = driver.find_element(By.XPATH,'//*[@id="TB_101685670"]')
        dateField.send_keys(d)
        DownloadCSV = driver.find_element(By.XPATH, '//*[@id="BTN_101685706"]')
    #Confirm that button was found
        if len(DownloadCSV) > 0
            DownloadCSV.click()
    except:
        dateField = driver.find_element(By.XPATH,'//*[@id="TB_101685670"]')
        x.Type(d)
        # use UI Item Explorer to find the X,Y coordinates of button
        x.MoveCursor(438, 435)
        # click on button
        x.MouseLeftClick
    x.Wait(2000)

解决这个问题的一种方法是相对于一些静态Id查找所需的元素/按钮,而不是直接转到元素的动态Id

我不知道确切的XPath,但是例如,包装日期输入的div的Id为PFC_Public_Bids_date_from,因此您可以尝试以下操作

dateField = driver.find_element(By.XPATH,'//*[@id="PFC_Public_Bids_date_from"]//input')。你知道吗

类似地,按钮可能类似于:

DownloadCSV = driver.find_element(By.XPATH, '//*[@id="CsvExportButton"]//button')

相关问题 更多 >