簡體   English   中英

木偶:選擇器中的方括號逸出

[英]Puppeteer: Escape square brackets in selector

我需要選擇ID包含方括號的元素。

#element[0]

但是,我不斷得到:

錯誤:找不到與選擇器“ element [0]”匹配的元素

我已經用\\逃避了選擇器中的元素,但這是行不通的。

page.select("#fruit\[0\]", "apples")

雙反斜杠轉義符也不起作用。 即:

page.select("#fruit\\[0\\]", "apples")

更新:我正在嘗試選擇的元素:

<select id="fruit[0]">
  <option>Please make a selection</option>
  <option>apples</option>
</select>

注意:即使我嘗試對上面的查詢使用page.waitFor方法,我也會收到相同的錯誤。

使用[id="fruit[0]"]

您可以使用CSS 屬性選擇器來引用元素的id屬性:

await page.waitFor( '[id="fruit[0]"]' );

await page.select( '[id="fruit[0]"]', 'apples' );

使用編碼數據轉義

如果您甚至嘗試在瀏覽器上執行document.querySelector('#fruit[0]') ,也會遇到相同的錯誤。 轉義不起作用,因為到偽造者讀取它時,它已經被解析並且沒有相同的轉義值。 逃脫它們的幾種方法。

說我們有一個這樣的元素,

<a href="/" id="sample[112]">Bar</a>

現在,如果您想使用vanila JS,可以嘗試以下方法,

在此處輸入圖片說明

內容如下:

< document.querySelector(CSS.escape('#sample[112]'))
> null

< document.querySelector('#sample[112]')
> Uncaught DOMException: Failed to execute 'querySelector' on 'Document': '#sample[112]' is not a valid selector.

< document.querySelector('#sample\5b 112\5d')
> ncaught DOMException: Failed to execute 'querySelector' on 'Document': '#sampleb 112d' is not a valid selector.

< document.querySelector('#sample\\5b 112\\5d')
> <a href="/" id="sample[112]">Bar</a>

如您在上面看到的,左括號為5b ,右括號為5d ,我們甚至不得不轉義該5d並不得不留出空間,以便瀏覽器可以解析它。

您應該嘗試上述代碼,然后找到適合您網站的代碼。

真實案例腳本

面對現實,您的目標網站沒有任何選擇的價值。 最好的方法是通過文本選擇,從此答案中無恥地復制。

另外,我可以對它進行兩次轉義並獲取數據,而無需對其進行編碼。 畢竟,nodeJS與瀏覽器控制台不同,並且在使用腳本時,所有動作都將有所不同。

用於HTML的源代碼,

<select id="sample[1]"><option>mango</option><option>apple</option></select>

還有用於測試的操縱up代碼,

const puppeteer = require("puppeteer");

function setSelectByText(selector, text) {
  // Loop through sequentially//
  const ele = document.querySelector(selector);
  console.log(ele);

  for (let ii = 0; ii < ele.length; ii++) {
    if (ele.options[ii].text == text) {
      // Found!
      ele.options[ii].selected = true;
      return true;
    }
  }
  return false;
}

puppeteer.launch().then(async browser => {
  console.log("Opening browser");
  const page = await browser.newPage();

  console.log("Going to site");
  await page.goto("http://0.0.0.0:8080"); // temporary website created for testing

  await page.evaluate(setSelectByText, "#sample\\[1\\]", "apple"); // we can use this over and over, without creating a separate function, just passing them as arguments

  await page.screenshot({ path: "test.png" });

  await browser.close();
});

在此處輸入圖片說明

您可能未正確引用ID。

如果您在創建HTML元素(例如fruit[0]fruit[1] )時以編程方式生成ID,則存儲的是值而不是引用。

示例:我有一個數組fruit = [apple, banana]並創建了一個元素... <button id=fruit[0]>Click me</button>如果要選擇該按鈕,則需要page.select('#apple') 代替 page.select('#fruit[0]')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM