2

I've been trying for some hours to grab the response from the imgur API. I got the XML in the terminal, but I don't know how to grab it and parse it. Here's my code.

c = pycurl.Curl()
values = [
          ("key", "Super Secret API Number"),
          ("image", (c.FORM_FILE, "pic.jpg"))]

c.setopt(c.URL, "http://api.imgur.com/2/upload.xml")
c.setopt(c.HTTPPOST, values)
c.perform()
c.close()

I'm a big noob with python, this is my first time. Python virgin. I read that you can parse the xml with ElementTree, but I can't find any cool documentation.

Hope you can help me. Thanks.

1
  • You could try using the nice python requests github.com/kennethreitz/requests when building http requests :) Commented Jan 24, 2012 at 23:38

2 Answers 2

3

Store the response from imgur-api into a file.Than need to use a xml parser to parse the xml response/file you are getting from Imgur-API.

There are lots of option available like lxml or BeautifulSoup.

Here is an example of how to use lxml with XPath expressions.

from lxml import etree


xml = """<foo>baz!</foo>"""

>>> xml = """<foo>baz!</foo>"""
>>> xp = etree.fromstring(xml)
>>> values = xp.xpath("//foo/text()")
>>> values
['baz!']

If you need to parse a xml file:

# parse from file
et = etree.parse(source_xml)
value = et.xpath("your xpath xpr here")

If you need to parse directly from url

# parse from URL
etree.parse("http://example.com/somefile.xml")

For, XPath use firefox's firebug extension or install firepath

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot. Didn't think about that, sounds logic.
@AlejandroAr: xpath is quite logical you can even try using cssselect with lxml. Use firebug to copy csspath of required element.
1

When I started using the included ElementTree module I found the documentation lacking good examples (currently there are only 3, and only one of those shows anything immediately practical).

I've answered a couple of questions here on SO related to lxml/ElementTree, and I usually see people getting stuck trying to write these weird list comprehensions to deal with something XPath handles in one line much more clearly:

If you have a more specific question, please post some source XML and desired effect.

I hope this helps,

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.