lxml:在属性中拆分?

时间:2011-06-13 12:33:52

标签: python html xpath screen-scraping lxml

我正在使用lxml来抓取一些看起来像这样的HTML:

<div align=center><a style="font-size: 1.1em">Football</a></div>
<a href="">Team A</a>
<a href="">Team B</a>
<div align=center><a style="font-size: 1.1em">Baseball</a></div>
<a href="">Team C</a>
<a href="">Team D</a> 

如何以表格

结束数据
[ {'category': 'Football', 'title': 'Team A'},
{'category': 'Football', 'title': 'Team B'},
{'category': 'Baseball', 'title': 'Team C'},
{'category': 'Baseball', 'title': 'Team D'}]

到目前为止,我已经:

results = []
for (i,a) in enumerate(content[0].xpath('./a')):
     data['text'] = a.text
     results.append(data)

但我不知道如何通过分割font-size并保留兄弟标签来获取类别名称 - 任何建议?

谢谢!

2 个答案:

答案 0 :(得分:3)

我使用以下代码取得了成功:

#!/usr/bin/env python

snippet = """
<html><head></head><body>
<div align=center><a style="font-size: 1.1em">Football</a></div>
<a href="">Team A</a>
<a href="">Team B</a>
<div align=center><a style="font-size: 1.1em">Baseball</a></div>
<a href="">Team C</a>
<a href="">Team D</a>
</body></html>
"""

import lxml.html

html = lxml.html.fromstring(snippet)
body = html[1]

results = []
current_category = None

for element in body.xpath('./*'):
    if element.tag == 'div':
        current_category = element.xpath('./a')[0].text
    elif element.tag == 'a':
        results.append({ 'category' : current_category, 
            'title' : element.text })

print results

它将打印:

[{'category': 'Football', 'title': 'Team A'}, 
 {'category': 'Football', 'title': 'Team B'}, 
 {'category': 'Baseball', 'title': 'Team C'}, 
 {'category': 'Baseball', 'title': 'Team D'}]

刮痧是脆弱的。例如,我们明确依赖于元素的排序以及嵌套。但是,有时这种硬连线方法可能足够好。


这是使用preceding-sibling轴的另一种(更多面向xpath的方法):

#!/usr/bin/env python

snippet = """
<html><head></head><body>
<div align=center><a style="font-size: 1.1em">Football</a></div>
<a href="">Team A</a>
<a href="">Team B</a>
<div align=center><a style="font-size: 1.1em">Baseball</a></div>
<a href="">Team C</a>
<a href="">Team D</a>
</body></html>
"""

import lxml.html

html = lxml.html.fromstring(snippet)
body = html[1]

results = []

for e in body.xpath('./a'):
    results.append(dict(
        category=e.xpath('preceding-sibling::div/a')[-1].text,
        title=e.text))

print results

答案 1 :(得分:1)

此外,如果你正在寻找其他方式(只是一个选项 - 不要打我太多)如何做到这一点或你没有能力导入lxml你可以使用以下 怪异 代码:

text = """
            <a href="">Team YYY</a>
            <div align=center><a style="font-size: 1.1em">Polo</a></div>
            <div align=center><a style="font-size: 1.1em">Football</a></div>
            <a href="">Team A</a>
            <a href="">Team B</a>
            <div align=center><a style="font-size: 1.1em">Baseball</a></div>
            <a href="">Team C</a>
            <a href="">Team D</a>
            <a href="">Team X</a>
            <div align=center><a style="font-size: 1.1em">Tennis</a></div>
        """
# next variables could be modified depending on what you really need        
keyStartsWith = '<div align=center><a style="font-size: 1.1em">'
categoryStart = len(keyStartsWith)
categoryEnd = -len('</a></div>')
output = []
data = text.split('\n')    
titleStart = len('<a href="">')
titleEnd = -len('</a>')

getdict = lambda category, title: {'category': category, 'title': title}

# main loop
for i, line in enumerate(data):
    line = line.strip()
    if keyStartsWith in line and len(data)-1 >= i+1:
        category = line[categoryStart: categoryEnd]
        (len(data)-1 == i and output.append(getdict(category, '')))
        if i+1 < len(data)-1 and keyStartsWith in data[i+1]:
            output.append(getdict(category, ''))
        else:
            while i+1 < len(data)-1 and keyStartsWith not in data[i+1]:
                title = data[i+1].strip()[titleStart: titleEnd]
                output.append(getdict(category, title))
                i += 1