且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我可以使用python,selenium和lxml解析xpath吗?

更新时间:2022-03-12 23:23:47

lxml的ElementTree具有.xpath()方法(请注意,Python分发主体中xml包中的ElementTree具有该方法!)

lxml's ElementTree has a .xpath() method (note that the ElementTree in the xml package in the Python distribution dosent have that!)

例如

# see http://lxml.de/xpathxslt.html

from lxml import etree

# root = etree.parse('/tmp/stack-overflow-questions.xml')
root = etree.XML('''
        <answers>
            <answer author="dlam" question-id="13965403">AAA</answer>
        </answers>
''')

all_answers = root.xpath('.//answer')

for i, answer in enumerate(all_answers):
    who_answered = answer.attrib['author']
    question_id = answer.attrib['question-id']
    answer_text = answer.text
    print 'Answer #{0} by {1}: {2}'.format(i, who_answered, answer_text)