我的應(yīng)用程序從數(shù)據(jù)庫中獲取 ID 列表。我用游標(biāo)遍歷這些,對于每個 ID,我將它插入帶有 Selenium 的 URL 以獲取頁面上的特定項目。這是對關(guān)鍵字進行搜索并獲得與該搜索最相關(guān)的項目。數(shù)據(jù)庫中有大約1000 個結(jié)果。在隨機迭代中,驅(qū)動程序中的 1 個操作將拋出一個StaleElementReferenceError完整的消息:過時的元素引用:元素未附加到頁面文檔\n(會話信息:chrome=77.0.3865.75)查看官方文檔,我可以看到導(dǎo)致此問題的兩個常見原因是:該元素已被完全刪除。該元素不再附加到 DOM。前者是最常見的原因。index.jsconst { MongoClient, ObjectID } = require('mongodb')const fs = require('fs')const path = require('path')const { Builder, Capabilities, until, By } = require('selenium-webdriver')const chrome = require('selenium-webdriver/chrome')require('dotenv').config()async function init() { try { const chromeOpts = new chrome.Options() const ids = fs.readFileSync(path.resolve(__dirname, '..', 'data', 'primary_ids.json'), 'utf8') const client = await MongoClient.connect(process.env.DB_URL || 'mongodb://localhost:27017/test', { useNewUrlParser: true }) const db = client.db(process.env.DB_NAME || 'test') const productCursor = db.collection('product').find( { accountId: ObjectID(process.env.ACCOUNT_ID), primaryId: { $in: JSON.parse(ids) } }, { _id: 1, primaryId: 1 } ) const resultsSelector = 'body #wrapper div.src-routes-search-style__container--2g429 div.src-routes-search-style__products--3rsz9' const mostRelevantSelector = `${resultsSelector} > div:nth-child(2) } }為了調(diào)試,我try...catch在每個驅(qū)動程序操作周圍放置了一個,以查看它是哪個特定操作失敗但不起作用,因為它從來都不是失敗的一致操作。例如,有時如果本來是其中elementLocated一行或其他行,則它只是getAttribute動作。如果在那種情況下是后者,這就是為什么我很困惑為什么會拋出這個錯誤,因為 selenium 肯定已經(jīng)在頁面上找到了元素(即link)但無法getAttribute('src')在元素上做?這就是為什么我對我得到的錯誤感到困惑。我想我在設(shè)置 selenium 以處理迭代的方式上一定做錯了。迭代次數(shù)永遠(yuǎn)不會超過110
迭代中的 StaleElementReferenceError
嗶嗶one
2021-10-14 17:29:18