靓汤:获取子节点的内容

2024-05-19 21:38:06 发布

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

我有以下python代码:

def scrapeSite(urlToCheck):
    html = urllib2.urlopen(urlToCheck).read()
    from BeautifulSoup import BeautifulSoup
    soup = BeautifulSoup(html)
    tdtags = soup.findAll('td', { "class" : "c" })
    for t in tdtags:
            print t.encode('latin1')

这将返回以下html代码:

^{pr2}$

我想得到a节点(例如FOO或BAR)之间的文本,即t。目录.目录. 不幸的是,这并不容易:) 有人知道怎么解决这个问题吗?在

非常感谢,任何帮助都将不胜感激!在

干杯, 约瑟夫


Tags: 代码fromimport目录readdefhtmlurllib2
2条回答

在本例中,可以使用t.contents[1].contents[0]来获取FOO和BAR。在

问题是contents返回一个包含所有元素(标记和NavigableStrings)的列表,如果您打印内容,您可以看到

[u'\n', <a href="more.asp">FOO</a>, u'\n']

因此,要获得实际的标记,您需要访问contents[1](如果您有完全相同的内容,这可能会因源HTML而异),在找到适当的索引之后,可以使用contents[0]来获取a标记中的字符串。在

现在,由于这取决于HTML源代码的确切内容,所以它非常脆弱。一个更通用和健壮的解决方案是再次使用find()通过t.find('a')找到“A”标记,然后使用contents列表来获取其中的值t.find('a').contents[0],或者仅仅使用t.find('a').contents来获得整个列表。在

对于您的特定示例,pyparsing的makeHTMLTags可能很有用,因为它们可以容忍HTML标记中的许多HTML变量,但为结果提供了一个方便的结构:

html = """
<td class="c"> 
<a href="more.asp">FOO</a> 
</td> 
<td class="c"> 
<a href="alotmore.asp">BAR</a> 
</td> 
<td class="d"> 
<a href="alotmore.asp">BAZZ</a> 
</td> 
"""

from pyparsing import *

td,tdEnd = makeHTMLTags("td")
a,aEnd = makeHTMLTags("a")
td.setParseAction(withAttribute(**{"class":"c"}))

pattern = td + a("anchor") + SkipTo(aEnd)("aBody") + aEnd + tdEnd

for t,_,_ in pattern.scanString(html):
    print t.aBody, '->', t.anchor.href

印刷品:

^{pr2}$

相关问题 更多 >