Home > other >  NameError: name 'fetch' is not defined in Selenium Console
NameError: name 'fetch' is not defined in Selenium Console

Time:11-12

Hi I am trying to open Selenium, visit a URL then use driver.execute_script to send a fetch request via Console in Chrome Developer Tools within the Selenium window.

However when I run it, the Selenium window opens up, visits the page, but when it gets to the execute_script section, it comes up with:

'NameError: name 'fetch' is not defined'. How do I fix this? Thanks

driver.get(URL1)
driver.get('URL')

payload = fetch("URL", {
  "headers": {
    "accept": "application/json, text/javascript, */*; q=0.01",
    "accept-language": "en-GB,en-US;q=0.9,en;q=0.8",
    "content-type": "application/x-www-form-urlencoded; charset=UTF-8",
    "sec-ch-device-memory": "8",
    "sec-ch-ua": "\"Google Chrome\";v=\"107\", \"Chromium\";v=\"107\", \"Not=A?Brand\";v=\"24\"",
    "sec-ch-ua-arch": "\"x86\"",
    "sec-ch-ua-full-version-list": "\"Google Chrome\";v=\"107.0.5304.88\", \"Chromium\";v=\"107.0.5304.88\", \"Not=A?Brand\";v=\"24.0.0.0\"",
    "sec-ch-ua-mobile": "?0",
    "sec-ch-ua-model": "",
    "sec-ch-ua-platform": "\"Windows\"",
    "sec-fetch-dest": "empty",
    "sec-fetch-mode": "cors",
    "sec-fetch-site": "same-origin",
    "x-esro-af": "s9TeAPYWl4s=",
    "x-requested-with": "XMLHttpRequest"
  },
  "referrer": "URL",
  "referrerPolicy": "strict-origin-when-cross-origin",
  "body": URL CONTENT",
  "method": "POST",
  "mode": "cors",
  "credentials": "include"
});

driver.execute_script(f'{payload}')

I have tried putting "" to wrap the whole payload but it doesn't work.

CodePudding user response:

That's not how fetch works. first of all it runs in the browser, and second it's async so use execute_async_script.

It should look something like this:

let response = driver.execute_async_script("""
  let [resolve] = arguments
  fetch(url, options).then(r => r.text()).then(resolve)
""")
  • Related