如何使用靓汤获得元素的位置?

2024-06-02 05:50:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我在HTML文档中有一个固定元素,我需要得到它的位置:

它的方法是什么?你知道吗

我试过:

from bs4 import BeautifulSoup

markup = open("myFile.html")
soup = BeautifulSoup(markup=markup.read(), features='html.parser')
markup.close()

spans = soup.find_all('span')
for sp in spans:
    print(sp.get('style'))

它返回None

元素:

<span class="ocrx_word" id="word_1_304" title="bbox 1459 1183 1505 1205; x_wconf 77" contenteditable="true" style="font-family: sans-serif; position: fixed; left: 1459px; top: 1183px; width: 46px; height: 22px;">DC</span>

位置如下:

element.style {
 font-family: sans-serif;
 position: fixed;
 left: 1459px;
 top: 1183px;
 width: 46px;
 height: 22px;
}

Tags: 元素stylehtmlpositionfamilyspwordspan
1条回答
网友
1楼 · 发布于 2024-06-02 05:50:12

使用css selector并搜索span tag with style属性。你知道吗

from bs4 import BeautifulSoup
html='''<span class="ocrx_word" id="word_1_304" title="bbox 1459 1183 1505 1205; x_wconf 77" contenteditable="true" style="font-family: sans-serif; position: fixed; left: 1459px; top: 1183px; width: 46px; height: 22px;">DC</span>'''

soup=BeautifulSoup(html,"html.parser")

for item in soup.select("span[style]"):
    print(item['style'])

相关问题 更多 >