使用 BeautifulSoup 在 python 中的链接标签之间提取文本 [英] Extract text between link tags in python using BeautifulSoup
本文介绍了使用 BeautifulSoup 在 python 中的链接标签之间提取文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个这样的 html 代码:
I have an html code like this:
<h2 class="title"><a href="http://www.gurletins.com">我的主页</a></h2>
<h2 class="title"><a href="http://www.gurletins.com/sections">Sections</a></h2>
我需要提取a"标签之间的文本(链接描述).我需要一个数组来存储这些:
I need to extract the texts (link descriptions) between 'a' tags. I need an array to store these like:
a[0] = "我的主页"
a[0] = "My HomePage"
a[1] = "部分"
a[1] = "Sections"
我需要使用 BeautifulSoup 在 python 中执行此操作.
I need to do this in python using BeautifulSoup.
请帮帮我,谢谢!
推荐答案
你可以这样做:
import BeautifulSoup
html = """
<html><head></head>
<body>
<h2 class='title'><a href='http://www.gurletins.com'>My HomePage</a></h2>
<h2 class='title'><a href='http://www.gurletins.com/sections'>Sections</a></h2>
</body>
</html>
"""
soup = BeautifulSoup.BeautifulSoup(html)
print [elm.a.text for elm in soup.findAll('h2', {'class': 'title'})]
# Output: [u'My HomePage', u'Sections']
这篇关于使用 BeautifulSoup 在 python 中的链接标签之间提取文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文