2012-03-21 27 views
1

djangoでlxml.etree.parsetree.xpathを使用して、外部のRSSフィードの内容を解析しようとしています。しかし何らかの理由で、私は結果を得ることができません。私は他のXMLファイルで成功するために以下のメソッドを使用することができましたが、これでは難しそうです。ここでlxml.etree.parseとtree.xpathを使ってdjangoで結果が得られないのはなぜですか?

は、xmlファイルは、私がからこすりしようとしていますことを次のようになります。ここでは

<feed xmlns="http://www.w3.org/2005/Atom"> 
    <title>Open Library : Author Name</title> 
    <link href="http://www.somedomain.org/people/atom/author_name" rel="self"/> 
    <updated>2012-03-20T16:41:00Z</updated> 
    <author> 
     <name>somedomain.org</name> 
    </author> 
    <id>tag:somedomain.org,2007:/person_feed/123456</id> 
    <entry> 
     <link href="http://www.somedomain.org/roll_call/show/1234" rel="alternate"/> 
     <id> 
     tag:somedomain.org,2012-03-20:/roll_call_vote/1234 
     </id> 
     <updated>2012-03-20T16:41:00Z</updated> 
     <title>Once upon a time</title> 
     <content type="html"> 
     This os a book full of words 
     </content> 
    </entry> 
</feed> 

はジャンゴでの私の見解は次のようになります。

def openauthors(request): 

    tree = lxml.etree.parse("http://www.somedomain.org/people/atom/author_name") 
    listings = tree.xpath("//author") 

    listings_info = [] 

    for listing in listings: 
     this_value = { 
      "name":listing.findtext("name"), 
      } 

     listings_info.append(this_value) 


    json_listings = '{"listings":' + simplejson.dumps(listings_info) + '}' 

    if("callback" in request.GET.keys()): 
     callback = request.GET["callback"] 
    else: 
     callback = None 

    if(callback): 
     response = HttpResponse("%s(%s)" % (
       callback, 
       simplejson.dumps(listings_info) 
       ), mimetype="application/json" 
      ) 
    else: 
     response = HttpResponse(json_listings, mimetype="application/json") 
    return response 

私はまた、いくつかのを試してみました彼らが助けても成功しないことを望んでいる以下の道。

listings = tree.xpath("feed/author") 
    listings = tree.xpath("/feed/author") 
    listings = tree.xpath("/author") 
    listings = tree.xpath("author") 

正しい方向への助けに感謝します。

答えて

0

おそらく問題は名前空間です。 lxmlモジュールは、タグ名の先頭に名前空間名を付加するので、xpath式がこの名前空間接頭辞と一致しないことが多分問題です。あなたがタグ名を見ている要素を反復し、あなたがこのような何かを得る場合、これは問題です:

>>> for element in tree: 
...  element 
[...] 
<Element {http://www.w3.org/2005/Atom}author at 7f14e75d1788> 
[...] 

は接頭辞「{http://www.w3.org/2005/Atom}」タグ名の前に「著者」というチェックしてください。

Need Help using XPath in ElementTree 、ここで:

python: xml.etree.ElementTree, removing "namespaces"

も多分名前空間接頭辞なしで解析するためのオプションがありますので、公式ドキュメントをチェックアウト その場合は、ここで見てください。

GL。

+0

うまくいきましたが、何もできませんでした。いくつかのコード例のいくつかのバリエーションを試しましたが、成功しませんでした。私は 'namespace =" {http://www.w3.org/2005/Atom} "' 'listings = tree.findall( '{%s} author /'%namespace}'を追加し、 'listing = treeを削除しました。 xpath( "// author") 'しかし、それは同じ結果で終わるようです:( – bigmike7801

+0

名前空間は問題であったが、あなたの解決策は私が探していたものではありませんでした。 – bigmike7801

関連する問題