0

I have a code like this :

import requests

user_agent_url = 'http://www.user-agents.org/allagents.xml'
xml_data = requests.get(user_agent_url).content

Which will parse a online xml file into xml_data. How can I parse it from a local disk file? I tried replacing with path to local disk,but got an error:

raise InvalidSchema("No connection adapters were found for '%s'" % url)

InvalidSchema: No connection adapters were found

What has to be done?

qwww
  • 1,313
  • 4
  • 22
  • 48
  • see this: https://stackoverflow.com/questions/12509888/how-can-i-send-an-xml-body-using-requests-library – Badri Gs Apr 03 '18 at 05:28
  • 1
    Get the file content with : https://docs.python.org/2/library/urllib2.html request (Get online remote file) and then parse it with https://docs.python.org/2/library/xml.etree.elementtree.html (Parse saved local file) – f14284 Apr 03 '18 at 05:28
  • The API Call and Data Parsing: https://sdbrett.com/BrettsITBlog/2017/03/python-parsing-api-xml-response-data/ – Badri Gs Apr 03 '18 at 05:30
  • there is no need for remote file..file is in my local system – qwww Apr 03 '18 at 05:30
  • Then use : docs.python.org/2/library/xml.etree.elementtree.html – f14284 Apr 03 '18 at 05:31
  • Badri GS.. It worked – qwww Apr 03 '18 at 05:35
  • f14282...I got this error : TypeError: a bytes-like object is required, not 'xml.etree.ElementTree.Element' – qwww Apr 03 '18 at 05:41

2 Answers2

3

Note that the code you quote does NOT parse the file - it simply puts the XML data into xml_data. The equivalent for a local file doesn't need to use requests at all: simply write

with open("/path/to/XML/file") as f:
    xml_data = f.read()

If you are determined to use requests then see this answer for how to write a file URL adapter.

holdenweb
  • 33,305
  • 7
  • 57
  • 77
2

You can read the file content using open method and then use elementtree module XML function to parse it.

It returns an etree object which you can loop through.

Example

Content = open("file.xml").read()
From xml.etree import XML
Etree = XML(Content)
Print Etree.text, Etree.value, Etree.getchildren()
user3001658
  • 41
  • 1
  • 3