python - 如何获取 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
元素在浏览器中显示的时间?
解决方案
通常不可能,因为坐标取决于给定浏览器的精确呈现方式。
但是您可以在 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/
推荐阅读
- c - 程序找不到显式链接的 DLL
- ios - 在 ARKit 的 GL 着色器中使用纹理
- email - Laravel:使用队列发送邮件忽略区域设置
- c# - 您是否知道在 asp.net Web 应用程序中的 httpruntime 标记处可以在服务器上获得更大的请求长度的替代方案?
- rest - REST API 命名约定 创建或更新资源的最佳实践
- spring - Static resource mapping in Spring3
- javascript - Javascript 滚动和验证表单
- cloud - 如何在juju的ocata openstack中部署多区域?
- python - 同比 年初至今 百分比变化
- java - 使用 COUNT(*) 从 netbean 中的多个表中计算多行