Python获取网络数据:从Socket到JSON/XML解析
本文详解Python获取网络数据的多种方法。从底层Socket通信原理出发,介绍利用urllib库简化HTTP请求的操作,并深入讲解如何使用ElementTree解析XML数据,以及利用json库高效处理JSON格式数据,为网络爬虫和数据抓取提供实用指南。
通过HTTP协议获取网络数据
Python语言内置了socket模块,支持建立网络连接并提取远程数据。
Socket提供双向通信通道,允许对同一连接进行读写。例如,A端向Socket写入信息并发送给连接另一端的B;B端读取Socket内容即可获取A的信息。然而,若A未发送信息而B持续尝试读取,双方将陷入无限等待。为此引入了通信协议,通过规定发送与响应的顺序来避免此类阻塞问题。
import socket
mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
mysock.connect(('fakeserver.com', 80)) # connect to server
cmd = 'GET http://fakeserver.com/fake.txt HTTP/1.0\r\n\r\n'.encode()
# send GET command followed by a blank line
mysock.send(cmd)
while True: # receive data and print out
data = mysock.recv(512)
if (len(data) < 1):
break
print(data.decode())
mysock.close()
使用urllib库获取数据
借助Socket可与网站服务器或邮件服务器建立连接,但在此之前需查阅文档以了解通信协议并编写相应程序。相比这种底层实现,使用更简单的Python包更为便捷。
通过 urllib.urlopen() 打开网页后,即可像读取本地文件一样读取其中的数据。
import urllib.request
fhand = urllib.request.urlopen('http://fakeserver.com/fake.txt')
for line in fhand:
#convert UTF-8 to unicode string and print out
print(line.decode().strip())
由于urllib使用简洁方便,它常被用于网络爬虫开发。除了读取网页数据外,爬虫还需从HTML格式中提取可用数据,因此除了urllib,另一个常用工具是BeautifulSoup。
import urllib.request, urllib.parse, urllib.error
from bs4 import BeautifulSoup
import ssl
# Ignore SSL certificate errors
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
html = urllib.request.urlopen('http://fakeserver.com/fake.html', context=ctx).read()
soup = BeautifulSoup(html, 'html.parser')
tags = soup('a')
# Retrieve all of the anchor tags
for tag in tags:
print(tag.get('href', None))
从XML格式获取数据
在网络数据交换中,常用的数据格式主要有两种:XML和JSON。
XML结构类似于HTML,可视为一种树状结构。利用Python的ElementTree包,可以将XML文件转换为树形结构,从而方便后续提取有效数据。
import xml.etree.ElementTree as ET
data = '''
<person>
<name>Jack</name>
<phone>+123456789</phone>
<email office="yes"/>
</person>
'''
tree = ET.fromstring(data) # convert xml into a tree
print('Name:', tree.find('name').text)
print('Attr:', tree.find('email').get('office'))
从JSON格式获取数据
相较于XML,JSON结构更为简单,功能也不如XML强大。但JSON具有一个显著优势:可以直接映射到Python的字典(dictionaries)和列表(lists)中,使用非常实用。
我们可以直接利用Python内置的json包来解析JSON数据。
import json
data = '''
{
"name" : "Jack",
"phone" : {
"type" : "intl",
"number" : "+123456789"
},
"email" : {
"office" : "yes"
}
}
'''
info = json.loads(data) # convert json into a dictianary
print('Name:', info['name'])
print('Attr:', info['email']['office'])
作者:Yuki 出处:https://www.cnblogs.com/yukiwu/
以上就是python如何获取网络数据的详细内容,更多关于python获取网络数据的资料请关注本站其它相关文章!
本站声明
本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。













