Python 網路連線
載入import urllib.repuest
import urllib.request as requset
with request.urlopen(網址)as response:
data=response.read()
print(data)
可用JSON模組。
import urllib.request as request
with request.urlopen(src) as response:
data-respones.read()
print(data)
執行後如下:
decode("utf-8") #取得網站原始碼
import urllib.request as request
src="https://www.nyu.edu.tw"
with request.urlopen(src) as response:
data-respones.read().decode("utf-8") #取得網站原始碼
print(data)
抓台北是政府API
https://data.taipei/opendata/datalist/apiAccess?scope=
resourceAquire&rid=296acfa2-5d93-4706-ad58-e83cc951863c
resourceAquire&rid=296acfa2-5d93-4706-ad58-e83cc951863c
用 json 格式:
import urllib.request as request
import json
src="https://data.taipei/opendata/datalist/apiAccess?scope=
resourceAquire&rid=296acfa2-5d93-4706-ad58-e83cc951863c"
resourceAquire&rid=296acfa2-5d93-4706-ad58-e83cc951863c"
with request.urlopen(src) as response:
data=json.load(response) #用模組處理json資料格式
print(data)
data=json.load(response) #用模組處理json資料格式
print(data)
#公司名列表出來
clist=data["result"]["results"]
print(clist)
import urllib.request as request
import json
src="https://data.taipei/opendata/datalist/apiAccess?scope=
resourceAquire&rid=296acfa2-5d93-4706-ad58-e83cc951863c"
resourceAquire&rid=296acfa2-5d93-4706-ad58-e83cc951863c"
with request.urlopen(src) as response:
data=json.load(response) #用模組處理json資料格式
print(data) #公司名列表出來
clist=data["result"]["results"]
print(clist)
import urllib.request as request
import json
src="https://data.taipei/opendata/datalist/apiAccess?scope=
resourceAquire&rid=296acfa2-5d93-4706-ad58-e83cc951863c"
resourceAquire&rid=296acfa2-5d93-4706-ad58-e83cc951863c"
with request.urlopen(src) as response:
data=json.load(response) #用模組處理json資料格式
print(data)
#公司名列表出來
clist=data["result"]["results"]
for company in clist:
print(company["公司名稱"])
#公司名列表出來
資料存在檔案中:
with open("data.txt","w",encoding="utf-8") as file: # w複寫,a 追加沒 python3.83版本沒影響
for company in clist:
file.write(company["公司名稱"]+"\n")
import urllib.request as request
import json
src="https://data.taipei/opendata/datalist/apiAccess?scope=resourceAquire&rid=296acfa2-5d93-4706-ad58-e83cc951863c"
with request.urlopen(src) as response:
data=json.load(response) #用模組處理json資料格式
print(data)
#公司名列表出來
clist=data["result"]["results"]
for company in clist:
print(company["公司名稱"])
with open("data.txt","a",encoding="utf-8") as file:
for company in clist:
file.write(company["公司名稱"]+"\n")
產生一個data.txt檔
沒有留言:
張貼留言