Retrieving Data over HTTP
Python 內置了 sockets 可以實作與網路連接并通過 Python 提取資料的功能,
socket 是可以提供雙向連接的,我們可以對同一個 socket 進行讀寫操作,比方說,A 對 socket 寫入資訊,并且將其發送給 socket 連接另一端 B;那么 B 讀取 socket 的內容就可以得到 A 的資訊,但是這樣會有一個問題,比如說, A端并沒有發送任何資訊,而 B 端一直在嘗試讀取 socket 的內容,那么 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 = https://www.cnblogs.com/yukiwu/archive/2021/04/07/mysock.recv(512)
if (len(data) < 1):
break
print(data.decode())
mysock.close()
Retrieving Data with urllib
利用 socket 我們可以與網站服務器,郵件服務器等建立連接,但是在建立連接之前,我們需要查詢檔案了解通信協議,然后根據協議撰寫程式,所以相較于 socket 這種黑魔法,我們可以利用更為簡單的 Python Package,
利用 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))
Retrieving Data from XML
在網路交換資料,我們常用的格式有兩種,一是 XML; 二是 JSON,
XML 長得就像是 HTML 的近親,可以看做是樹的一種,利用 Python Package ElementTree 我們可以將 XML 檔案轉換為樹,這樣可以方便我們后續提取有效的資料,
import xml.etree.ElementTree as ET
datahttps://www.cnblogs.com/yukiwu/archive/2021/04/07/= '''
<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'))
Retrieving Data from JSON
JSON 結構相較于 XML 來說更為簡單,所以他的功能就沒有那么強大,但是 JSON 有一個優勢就是可以直接映射到 Python 的 dictionaries 和 lists 中,非常實用,
我們可以直接利用 Python Package json 來解釋 JSON,
import json
datahttps://www.cnblogs.com/yukiwu/archive/2021/04/07/= '''
{
"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'])
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/273520.html
標籤:其他
