python 3.7极速入门教程7互联网

本文教程目录

7互联网

互联网访问

urllib

urllib是用于打开URL的Python模块。

import urllib.request
# open a connection to a URL using urllib
webUrl  = urllib.request.urlopen('https://china-testing.github.io/address.html')

#get the result code and print it
print ("result code: " + str(webUrl.getcode()))

# read the data from the URL and print it
data = webUrl.read()
print (data)

图片.png

json

json是一种受JavaScript对象文字语法启发的轻量级数据交换格式。是目前互联网最流行的数据交换格式。

json公开了标准库marshal和pickle模块的用户所熟悉的API。

>>> import json
>>> json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}])
'["foo", {"bar": ["baz", null, 1.0, 2]}]'
>>> print(json.dumps("\"foo\bar"))
"\"foo\bar"
>>> print(json.dumps('\u1234'))
"\u1234"
>>> print(json.dumps('\\'))
"\\"
>>> print(json.dumps({"c": 0, "b": 0, "a": 0}, sort_keys=True))
{"a": 0, "b": 0, "c": 0}
>>> from io import StringIO
>>> io = StringIO()
>>> json.dump(['streaming API'], io)
>>> io.getvalue()
'["streaming API"]'

参考资料

XML

XML即可扩展标记语言(eXtensible Markup Language)。它旨在存储和传输中小数据量,并广泛用于共享结构化信息。

import xml.dom.minidom

doc = xml.dom.minidom.parse("test.xml");

# print out the document node and the name of the first child tag
print (doc.nodeName)
print (doc.firstChild.tagName)
# get a list of XML tags from the document and print each one
expertise = doc.getElementsByTagName("expertise")
print ("{} expertise:".format(expertise.length))
for skill in expertise:
    print(skill.getAttribute("name"))

# create a new XML tag and add it into the document
newexpertise = doc.createElement("expertise")
newexpertise.setAttribute("name", "BigData")
doc.firstChild.appendChild(newexpertise)
print (" ")

expertise = doc.getElementsByTagName("expertise")
print ("{} expertise:".format(expertise.length))
for skill in expertise:
    print (skill.getAttribute("name"))

图片.png

ElementTree是处理XML文件的简便方法。

import xml.dom.minidom
import xml.etree.ElementTree as ET

tree = ET.parse('items.xml')
root = tree.getroot()

# all items data
print('Expertise Data:')

for elem in root:
   for subelem in elem:
      print(subelem.text)

图片.png

参考资料

links