python中减去html div标签

发布于 2024-12-22 18:04:37 字数 761 浏览 2 评论 0原文

我们如何从Python中的Html字符串中减去div标签?

例如, 我的Html DOM就像

 <html>
 <div id ="main">
   <div id = "child1">
     ....(some doms)
   </div>
   <div id="child2">
      .......(some nested dom)
   </div>
 </div>
 </html>

在这个结构中我需要从“div #main”减去“div #child2”

div "main" - div "child2" = div "child1"

,即我需要以这种方式得到“div #child1”

为什么我想要这种方式是,

就“child1”而言" 包含动态广告(一些动态加载内容),它可能存在也可能不存在。我无法直接使用“child1”id 获取该内容

我已经在 BeautifulSoup() 中尝试过了。版本 = 3.0.7a

   >>>div = BeautifulSoup.BeautifulSoup('div',{'id':'child1'})
   >>>div
      []

您能否根据上述要求帮忙解决这个问题?

How we could subtract the div tags from the Html String in python?

For example,
My Html DOM is like

 <html>
 <div id ="main">
   <div id = "child1">
     ....(some doms)
   </div>
   <div id="child2">
      .......(some nested dom)
   </div>
 </div>
 </html>

In this structure I need to subtract from "div #main" to "div #child2"

div "main" - div "child2" = div "child1"

,ie I need to get "div #child1" in this way

Why I want this way is,

In terms of "child1" contains the dynamic ads(some dynamic loading contents),it may be present may not be also.I couldn't able to get that content directly using the "child1" id

I have tried it in BeautifulSoup() .version = 3.0.7a

   >>>div = BeautifulSoup.BeautifulSoup('div',{'id':'child1'})
   >>>div
      []

Could you please help to fix this with the above requirements?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

坚持沉默 2024-12-29 18:04:37

你的问题不是很清楚。您想获取某个元素之前的所有元素吗?

import lxml.html as lh

html = """
<div id="div1">
</div>
<div id="div2">
</div>
"""

tree = lh.fromstring(html)

for el in tree.xpath("div[@id='div2']/preceding-sibling::div"):
    print el.attrib['id']

结果:

div1

Your question isn't very clear. Are you wanting to get all elements before a certain element?

import lxml.html as lh

html = """
<div id="div1">
</div>
<div id="div2">
</div>
"""

tree = lh.fromstring(html)

for el in tree.xpath("div[@id='div2']/preceding-sibling::div"):
    print el.attrib['id']

Result:

div1
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文