beautifulsoup怎样获取两个标签间内容

shuzai 2015-10-18 10:32:25
        <div class="c">
<a href="/u/">
user
</a>
[所需内容]
<span class="cc">
bbb
</span>
<span class="ct">
ccc
</span>
</div>


我要获取 [所需内容] 的内容
这里面有可能是纯文本,也可能文本并且包含其他html标记,所以不能单纯的用find找到,用next_sibling 的话,如果只有单一内容就可以获取,如果有文本混杂其他html内容,又会漏掉信息
...全文
2697 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
SandyLsnSmile 2018-11-07
  • 打赏
  • 举报
回复


from bs4 import BeautifulSoup as bs
import bs4

html = """
<div class="c">
<a href="/u/">
user
</a>
[所需内容]<h2>title</h2>
<span class="cc">
bbb
</span>
<span class="ct">
ccc
</span>
</div>
"""

soup = bs(html, 'html.parser')
div = soup.find('div',class_='c')
all_contents = div.contents

IS_FIRST_a = True
IS_FIRST_span = True
index_a = 0
index_span = 0

for i, child in enumerate(all_contents):
print(i, '----', child)
if child.name == 'a' and IS_FIRST_a:
index_a = i
IS_FIRST_a = False
if child.name == 'span' and IS_FIRST_span:
index_span = i
IS_FIRST_span = False

print(index_a, index_span)
content = all_contents[index_a + 1:index_span]
print(content)
want_content = []
for text in content:
if type(text) is bs4.element.Tag:
want_content.append(text)
elif text.strip() != '':
want_content.append(text.strip())

print(want_content)

--------------------------------打印结果-------------------------------------
0 ----

1 ---- <a href="/u/">
user
</a>
2 ----
[所需内容]
3 ---- <h2>title</h2>
4 ----

5 ---- <span class="cc">
bbb
</span>
6 ----

7 ---- <span class="ct">
ccc
</span>
8 ----

1 5
['\n [所需内容]', <h2>title</h2>, '\n']
['[所需内容]', <h2>title</h2>]



请楼主看看是不是你想要的结果
阿丘的博客 2017-09-28
  • 打赏
  • 举报
回复
楼主的所需内容可以用a.next_element获取,这样子会获取a标签和它的子标签之间的内容
zhang010101 2016-06-24
  • 打赏
  • 举报
回复
你把网址发上来 我看看能不能爬出来
qq_26321115 2016-06-18
  • 打赏
  • 举报
回复
我也想问这个内容,请问楼主解决了吗
sprawling 2016-06-18
  • 打赏
  • 举报
回复
所需内容里面会不会出现[]符号?如果不会出现,用正则就可以解决啊。
_Neo 2015-10-27
  • 打赏
  • 举报
回复
如果可以,可以分析所需内容的内容构造,然后写个方法进行逻辑判断,不同情况下进行不同操作

37,719

社区成员

发帖
与我相关
我的任务
社区描述
JavaScript,VBScript,AngleScript,ActionScript,Shell,Perl,Ruby,Lua,Tcl,Scala,MaxScript 等脚本语言交流。
社区管理员
  • 脚本语言(Perl/Python)社区
  • IT.BOB
加入社区
  • 近7日
  • 近30日
  • 至今

试试用AI创作助手写篇文章吧