kobyt
kobyt

Reputation: 63

Selenium - Can't get text from element (Python)

I'm trying to get the result of an input from: https://web2.0calc.com/

But I can't get the result. I've tried:

result = browser.find_element_by_id("input")

result.text

result.get_attribute("textContent")

result.get_attribute("innerHtml")

result.get_attribute("textContent")

But it doesn't work and returns an empty string...

Upvotes: 0

Views: 1290

Answers (2)

Andersson
Andersson

Reputation: 52665

The required element is a Base64 image, so you can either get a Base64 value from @src, convert it to an image and get a value with a tool like PIL (quite complicated approach) or you can get a result with a direct API call:

import requests

url = 'https://web2.0calc.com/calc'
data = data={'in[]': '45*23'}  # Pass your expression as a value

response = requests.post(url, data=data).json()
print(response['results'][0]['out'])
#  1035

If you need the value of #input:

print(browser.find_element_by_id('input').get_attribute('value'))

Upvotes: 2

QHarr
QHarr

Reputation: 84455

My preference would be for the POST example (+ for that) given but you can grab the expression and evaluate that using asteval. There may be limitations on asteval. It is safer than eval.

from selenium import webdriver
from asteval import Interpreter

d = webdriver.Chrome()
url = 'https://web2.0calc.com/'
d.get(url)
d.maximize_window()
d.find_element_by_css_selector('[name=cookies]').click()
d.find_element_by_id('input').send_keys(5)
d.find_element_by_id('BtnPlus').click()
d.find_element_by_id('input').send_keys(50)
d.find_element_by_id('BtnCalc').click()
expression = ''

while len(expression) == 0:
    expression = d.find_element_by_id('result').get_attribute('title')

aeval = Interpreter()
print(aeval(expression))
d.quit()

Upvotes: 1

Related Questions