首页 > 解决方案 > 如何获取 HTML 元素坐标?

问题描述

我想知道是否有一种方法可以在不打开浏览器页面的情况下获取 HTML 页面中 HTML 元素的坐标。我正在使用 python,我看到你可以拉一些请求来获取 HTML 页面,然后,你可以使用模块在其中搜索,bs4但我没有找到获取元素坐标的方法,这可能吗?(对于元素坐标,我指的是浏览器加载页面时元素的x pos和)y pos

假设我想获取此页面的 HTML 文本 并且我已经写了这个

import requests
from bs4 import BeautifulSoup

data = requests.get("https://www.nike.com")
soup = BeautifulSoup(data.text, 'html.parser')

element = soup.find('p',{'class':"vVtA7wL6 headline-sm-base text-color-primary-dark"})

print(element.coords) # exists/can I create in some way a module that returns the coords?

有没有办法找到element.coords元素在浏览器中显示的时间?

标签: pythonbeautifulsouppython-requests

解决方案


通常不可能,因为坐标取决于给定浏览器的精确呈现方式。

但是您可以在 python 中打开一些浏览器,并运行一个检索坐标并将其返回给 python 的 javascript。我们将使用 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="http://wikipedia.org", 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必须在主线程中调用,它会阻塞它直到窗口被销毁。

有关 webview 包的详细信息,请参阅https://pywebview.flowrl.com/


推荐阅读