【问题标题】:How do I get the position of an element using Beautiful Soup?如何使用 Beautiful Soup 获取元素的位置?
【发布时间】:2019-11-25 22:42:43
【问题描述】:

我在 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;
}

【问题讨论】:

  • 为什么将markup 作为关键字参数传递?
  • 你可以使用sp["style"]之类的东西。那应该可以。
  • @ArmedinKuka 我收到错误KeyError: 'style'
  • @JohnGordon 有什么改变吗?
  • 由于它恰好在同一个位置,我认为它不会。我只是好奇你为什么要那样做。

标签: python html web beautifulsoup


【解决方案1】:

使用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'])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-23
    • 2013-08-21
    • 1970-01-01
    • 1970-01-01
    • 2013-08-19
    相关资源
    最近更新 更多