1. 程式人生 > 其它 >python requests庫的簡單運用

python requests庫的簡單運用

python

requests的簡單運用

使用pycharm獲取requests包

ctrl+alt+s Project:pythonProject pythoninterpreter 點+號搜尋

使用requests裡的socket達成區域網內通訊,UDP

import time   #server
import socket
try:
    s = socket.socket(type=socket.SOCK_DGRAM)  # 建立類
    hostname = socket.gethostname()  # 獲取自己的主機名
    s.bind((hostname, 8888))  # 繫結主機號與埠號
    msg,address=s.recvfrom(1024)
    print(time.strftime("%Y-%m-%d  %H:%M:%S",time.localtime(time.time())),
"服務端收到客戶端:%s的訊息:%s"%(address,msg.decode('utf-8')))
    data='可以正常通訊'.encode('utf-8')
    s.sendto(data,address)
    while True:
        a = input("傳送訊息(q = quit)")
        if a != "q":
            s.sendto(a.encode('utf-8'), address)
        else:
            break
        msg,address=s.recvfrom(1024)
        print(time.strftime("%Y-%m-%d  %H:%M:%S", time.localtime(time.time())),
            "服務端收到客戶端:%s的訊息:%s" % (address, msg.decode('utf-8')))
    s.close()
except Exception as e:
    print("出錯了", e)

import socket    #client
import time
try:
    s=socket.socket(type=socket.SOCK_DGRAM)
    hostname=socket.gethostname()
    data='連線成功'.encode('utf-8')
    s.sendto(data,(hostname,8888))
    responese,address=s.recvfrom(1024)
    print(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())),
'收到服務端%s的訊息:%s'%(address,responese.decode('utf-8')))
    n=0
    while n<1000:
        response,address = s.recvfrom(1024)
        print(time.strftime("%Y-%m-%d  %H:%M:%S", time.localtime(time.time())),
"收到服務端%s的訊息:%s" % (address, response.decode('utf-8')))
        a = input('傳送資訊')
        s.sendto(a.encode('utf-8'),address)
    s.close()
except Exception as e:
    print('出錯了',e)

使用requests裡的socket達成區域網內通訊,TCP

import socket   #server
import time
try:
    s = socket.socket()
    hostname = socket.gethostname()
    # 繫結套接字地址
    s.bind((hostname, 8888))
    s.listen(5)
    print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())), '服務端準備完畢,等待客戶端連線')
    con, address = s.accept()
    print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())),'客戶端已連線上服務端,連線地址:', address)
    message = '你好,我是服務端'
    # 傳送訊息,必須對傳送的內容進行編碼
    con.send(message.encode('utf-8'))
    print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())), '服務端傳送:', message)
    # 關閉套接字
    con.close()
except Exception as e:
    print('建立TCP服務端失敗', e)

import socket
import time
try:
    s = socket.socket()
    hostname = socket.gethostname()
    s.connect((hostname, 8888))
    response = s.recv(1024).decode('utf-8')   # 接收服務端訊息並解碼
    print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())), '收到服務端訊息:', response)
    s.close()    # 關閉套接字
except Exception as e:
    print('建立TCP客戶端失敗', e)

requests模組裡的get應用

import requests
word = input('請輸入搜尋內容')
pn = input('請輸入頁碼')
p={'kw':word,"pn":pn}
url='https://tieba.baidu.com/f'
headers={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:94.0) Gecko/20100101 Firefox/94.0'}
re=requests.get(url,headers=headers,params=p)
print(re.content.decode('utf-8'))

輸入圖片地址將結尾改成.jpg可以爬圖片

request模組裡的post應用

這裡使用post去給百度翻譯傳引數

import requests
import json
headers={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:93.0) Gecko/20100101 Firefox/93.0"}  
url='https://fanyi.baidu.com/sug'
while True:
    word = input('百度翻譯:')
    if word.lower() == 'quit':
        break
    data={"kw":word}
    re=requests.post(url,headers=headers,data=data)  #地址,偽裝的瀏覽器以及資料
    re_obj=re.json()   #把json格式寫進re_obj
    print(word+":"+re_obj['data'][0]['v'])        #指定re_obj裡的特定值
    filename=word+'.json'     #設定檔名
    fp=open(filename,"w",encoding='utf-8')      #以utf-8寫入檔案
    json.dump(re_obj,fp=fp,ensure_ascii=False)     #不允許json以ascii碼的形式寫入檔案

get是在url地址上加引數,post是在頁面裡面的文字欄加引數