Python Unsupported operand type pyppeteer

Asked

Viewed 56 times

0

I’m trying to use pyppeteer (a port from Puppeteer to python, with basically the same syntax).

When I try await page.mouse.click('.jfk-button-narrow', { 'button': 'left' }), the error arises

 File "C:\Users\Windows 7\Desktop\Scripts\ScriptsPython\PrimevalBrowserManipulator.py", line 9, in main
    await page.mouse.click('.jfk-button-narrow', { 'button': 'left' })
  File "C:\Users\Windows 7\AppData\Local\Programs\Python\Python36\lib\site-packages\pyppeteer\input.py", line 302, in click
    await self.move(x, y)
  File "C:\Users\Windows 7\AppData\Local\Programs\Python\Python36\lib\site-packages\pyppeteer\input.py", line 277, in move
    x = round(fromX + (self._x - fromX) * (i / steps))
TypeError: unsupported operand type(s) for -: 'str' and 'float'

in the attempt to select the 'exchange language' button in Google Translator. However the script works perfectly if I use something like await page.mouse.click(1066.0625, 135, { 'button': 'left' }) where I choose the exact pixel to be clicked on (which is not at all practical). So what’s wrong with the .jfk-button-narrow? It is exactly the element class of the 'exchange languages' button'.

My code:

import asyncio
from pyppeteer import launch
async def main():
    browser = await launch()
    page = await browser.newPage()
    await page.setViewport({ 'width': 1280, 'height': 560 })
    await page.goto('https://translate.google.com/?hl=pt-BR')
    await page.mouse.click('.jfk-button-img', { 'button': 'left' })
    await page.screenshot({'path': r'C:\Users\Windows 7\Desktop\yes.png'})
    await browser.close()
asyncio.get_event_loop().run_until_complete(main())

I checked the source and apparently the port for python does not accept id/class/name element but only pixel coordinates in the function page.mouse.click, yet I’m not sure.

  • Are you saying that it is not possible to perform the subtraction self._x - fromX when self._x is a string and fromX is a float.

1 answer

1


In order to click an element from your CSS selector, you need to use the implicit pyppeteer Elementhandle class on the page.click(selector) instead of page.mouse.click(coordinates). The corrected code will be:

import asyncio
from pyppeteer import launch
async def main():
    browser = await launch()
    page = await browser.newPage()
    await page.setViewport({ 'width': 1280, 'height': 560 })
    await page.goto('https://translate.google.com/?hl=pt-BR')
    await page.click('.jfk-button-img', button='left')
    await page.screenshot({'path': r'C:\Users\Windows 7\Desktop\yes.png'})
    await browser.close()
asyncio.get_event_loop().run_until_complete(main())

Browser other questions tagged

You are not signed in. Login or sign up in order to post.