How to get the height, width of HTML elements on PhantomJS of selenium

Asked 2 years ago, Updated 2 years ago, 79 views

http://www.tenki.jp/forecast/3/16/4410/13208.html
Obtain height, width of Chofu City Alarms and Warnings on this page

 from selenium import webdriver
URL="http://www.tenki.jp/forecast/3/16/4410/13105-daily.html"
driver=webdriver.PhantomJS()
driver.get (URL)
print(driver.execute_script("return document.getElementsByClassName('class')[1].offsetWidth;"))

[Reference]
https://stackoverflow.com/questions/42610379/how-to-get-a-websites-body-width-with-selenium-and-python
However, in the last line
raise exception_class(message, screen, stacktrace)
(Omitted)
Screenshot:available via screen
appears.
However, the last line is

 print(driver.execute_script("return document.body.offsetWidth;")    

However, the number 400 was returned, so I thought I could get the height of the element on the virtual browser.

I interpreted driver.execute_script() as a result of inserting js into the original html, so follow the DOM format

 document.getElementsByClassName('class')[1].offsetWidth

What is wrong with that?
https://developer.mozilla.org/ja/docs/Web/API/Document/getElementsByClassName

Also
https://stackoverflow.com/questions/15664000/how-to-programmatically-measure-the-elements-sizes-in-html-source-code-using-py
According to , it is possible to use a library called Ghost, but I do not want to include Pyside or PyQt, so I would like to know the solution with selenium.

javascript python html selenium

2022-09-30 16:05

1 Answers

""Screenshot:available via screen" is just a bonus at the end of the exception message saying, ""Please refer to the screenshot data when an error occurs in the exception object!"", which has nothing to do with the cause of the problem."
I think that the message that is directly related to the actual cause is printed in JSON format in the part where (omitted) just before that, so why don't you check it again?

By the way, when I ran the same code at my fingertips, the following JSON was returned:

{'errorMessage': "'undefined' is not an object(evaluing' document.getElementsByClassName('class')[1].offsetWidth')",
 'request': {'headers': {'Accept': 'application/json',
   'Accept-Encoding': 'identity',
   ...
}

In other words, document.getElementsByClassName('class')[1] is simply said to be undefined.

Reference

"Also, the above ""Screenshot data when an exception occurs"" can be retrieved as follows, so it may be helpful to solve the problem."

 from selenium.common.exception import WebDriverException
import base64

try:
    result=driver.execute_script(...)
except WebDriverException as:
    if.screen:
        with open('exception.png', 'wb') as f:
            f.write(base64.b64decode(e.screen))


2022-09-30 16:05

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.