一般来说不可能,因为坐标取决于给定的浏览器渲染它的方式。在
但是,您可以在python中打开一些浏览器,并运行一个javascript来检索坐标并将其返回给python。我们将使用pywebview作为浏览器(需要pip3 install pywebview)。在
打开浏览器窗口,使用JavaScript检查HTML元素,返回值,然后关闭浏览器窗口。注意这些值将取决于窗口大小。在import webview
from threading import Thread
def thread_fun():
while webview.evaluate_js('document.readyState') != "complete":
# wait for page to load
time.sleep(0.5)
# ask for a bounding rect
bounding_rect = webview.evaluate_js('''
document.querySelector("img.central-featured-logo").getBoundingClientRect()
''');
webview.destroy_window()
print(bounding_rect)
thread = Thread(target=thread_fun)
thread.start()
webview.create_window(title="a title", url="", width=500, height=700)
thread.join()
结果:{'x': 150, 'y': 176, 'width': 200, 'height': 183, 'top': 176, 'right': 350, 'bottom': 359, 'left': 150}
必须在主线程中调用webview.create_window,它会阻止它,直到窗口被破坏为止。在
如果觉得《python获取网页元素坐标_如何在python中获得HTML元素的坐标》对你有帮助,请点赞、收藏,并留下你的观点哦!