Skip to main content
 首页 » 编程设计

python之如何解析远程文件

2024年11月01日11jpfss

请帮忙解析网上的文档。

import pprint 
import xml.dom.minidom 
from xml.dom.minidom import Node 
 
import requests 
 
addr = requests.get('http://fh79272k.bget.ru/py_test/books.xml') 
print(addr.status_code) 
 
doc = xml.dom.minidom.parse(str(addr))          # load doc into object 
                                                  # usually parsed up front 
 
 
mapping = {} 
for node in doc.getElementsByTagName("book"):     # traverse DOM object 
    isbn = node.getAttribute("isbn")              # via DOM object API 
    L = node.getElementsByTagName("title") 
    for node2 in L: 
        title = "" 
        for node3 in node2.childNodes: 
            if node3.nodeType == Node.TEXT_NODE: 
                title += node3.data  
        mapping[isbn] = title 
 
# mapping now has the same value as in the SAX example 
pprint.pprint(mapping) 

这个脚本不起作用。错误信息是:

Traceback (most recent call last): File "C:\VINT\OPENSERVER\OpenServer\domains\localhost\python\parse_html\1\dombook.py", line 14, in doc = xml.dom.minidom.parse(str(addr)) # load doc into object File "C:\Python33\lib\xml\dom\minidom.py", line 1960, in parse return expatbuilder.parse(file) File "C:\Python33\lib\xml\dom\expatbuilder.py", line 908, in parse fp = open(file, 'rb') OSError: [Errno 22] Invalid argument: ''

XML:

<catalog> 
<book isbn="0-596-00128-2"> 
<title>Python & XML</title> 
<date>December 2001</date> 
<author>Jones, Drake</author> 
</book> 
<book isbn="0-596-15810-6"> 
<title>Programming Python, 4th Edition</title> 
<date>October 2010</date> 
<author>Lutz</author> 
</book> 
<book isbn="0-596-15806-8"> 
<title>Learning Python, 4th Edition</title> 
<date>September 2009</date> 
<author>Lutz</author> 
</book> 
<book isbn="0-596-15808-4"> 
<title>Python Pocket Reference, 4th Edition</title> 
<date>October 2009</date> 
<author>Lutz</author> 
</book> 
<book isbn="0-596-00797-3"> 
<title>Python Cookbook, 2nd Edition</title> 
<date>March 2005</date> 
<author>Martelli, Ravenscroft, Ascher</author> 
</book> 
<book isbn="0-596-10046-9"> 
<title>Python in a Nutshell, 2nd Edition</title> 
<date>July 2006</date> 
<author>Martelli</author> 
</book> 
<!-- 
 plus many more Python books that should appear here  
--> 
</catalog> 

请您参考如下方法:

您是从响应对象而不是正文中的文本构建 XML。代替 str(addr),使用 addr.text:

doc = xml.dom.minidom.parse(addr.text) 

此外,使用 XML 解析器来处理 HTML 也很麻烦。尝试使用 Beautiful Soup .