Python 网络编程

2018-08-28  本文已影响0人  FlyingLittlePG

网络

socket 库

socketserver 网络服务器框架模块

ftplib 模块

import ftplib

#定义回调函数,将retrbinary函数接收到的数据写入本地文件中
def file(data):
    with open(r'1.txt','wb')as f:
        f.write(data)

# 指定FTP的host,获得套接字连接
con = ftplib.FTP('ftp.acc.umu.se')

# 连接FTP服务器
con.connect()

# 匿名账户登录
con.login()

con.dir()

# 下载文件,并调用file函数,将数据写入本地文件
con.retrbinary('RETR robots.txt',file)

# 关闭连接
con.close()

email 电子邮件模块

Content-Type: text/plain; charset="utf-8"
MIME-Version: 1.0
Content-Transfer-Encoding: base64
From: mine<xxxx@163.com>
To: you<xxx@qq.com>
Subject: =?utf-8?b?6YKu5Lu25qCH6aKY?=

6L+Z5piv5LiA5Lu95paH5pys5raI5oGv6YKu5Lu2

smtplib SMTP简单邮件发送协议模块

poplib 邮局协议模块

http 超文本传输协议模块

# 创建一个cookie,使用了几种不同的方式
from http.cookies import *

cookie = SimpleCookie()

cookie["name"] = "mycookie"

dict = {'path':'/','comment':'这是cookie'}
cookie['name'].update(dict)

cookie['name']['domain'] = '127.0.0.1'

cookie['whatever'] = 'i dont know'

print(cookie)

cgi 通用网关接口支持模块、cgitb CGI脚本的回溯管理器模块

cgitb用于调试cgi脚本程序

cgi是服务器运行时调用的外部程序,通过通用CGI接口与服务器通信,默认放在['/cgi-bin', '/htbin']目录下

import cgi
import cgitb

cgitb.enable()

print("Content-Type: text/html")
print()

html ='''
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>My First Python CGI</h1>
</body>
</html>
'''
print(html)
# index.html中的内容
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>请输入文字</h1>
    <form action="http://127.0.0.1:8888/cgi-bin/cc.py" method="GET" id="myform">
        <h2>账户:<input type="text" name="usr"></h2>
        <h2>密码:<input type="text" name="pwd"></h2>
        <button type="submit">发送</button>
    </form>
</body>
</html>

# CGI程序
import cgi
import cgitb

cgitb.enable()

print("Content-Type: text/html")
print()

form = cgi.FieldStorage()
usr = form.getvalue('usr')
pwd = form.getvalue('pwd')
html ='''
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>获取到的数据是:</h1>
    <p>{0}</p>
    <p>{1}</p>
</body>
</html>
'''.format(usr,pwd)

print(html)
# index.html内容是
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>请勾选</h1>
    <form action="/cgi-bin/cc.py" method="POST" id="myform">
        <input type="checkbox" name="usr" value="on" > usr
        <input type="checkbox" name="pwd" value="on" > pwd
        <button type="submit">发送</button>
    </form>
</body>
</html>

# cgi程序
import cgi
import cgitb

cgitb.enable()

print("Content-Type: text/html")
print()

form = cgi.FieldStorage()
google = form.getvalue('google')
if google == on:
    r1 = 'google被选中'
else:
    r1 = 'google没有被选中'
baidu = form.getvalue('baidu')
if baidu == 'on':
    r2 = 'baidu被选中'
else:
    r2 = 'baidu没有被选中'
html ='''
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>获取到的数据是:</h1>
    <p>{0}</p>
    <p>{1}</p>
</body>
</html>
'''.format(r1,r2)

print(html)
# index.html中的内容
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>请勾选</h1>
    <form action="/cgi-bin/cc.py" method="POST" id="myform">
        <input type="radio" name="site" value="google" > 谷歌
        <input type="radio" name="site" value="baidu" > 百度
        <button type="submit">发送</button>
    </form>
</body>

# cgi程序内容
import cgi
import cgitb

cgitb.enable()

print("Content-Type: text/html")
print()

form = cgi.FieldStorage()
value = form.getvalue('site')

html ='''
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>获取到的数据是:</h1>
    <p>{0}</p>
</body>
</html>
'''.format(value)

print(html)
# index.html中的内容
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>请输入内容</h1>
    <form action="/cgi-bin/cc.py" method="post">
        <Textarea name="text" cols="40" rows="4" >在这里输入内容....
        </Textarea>
        <input type="submit">
    </form>
</body>
</html>

# cgi程序中的内容
import cgi
import cgitb

cgitb.enable()

print("Content-Type: text/html")
print()

form = cgi.FieldStorage()
value = form.getvalue('text')

html ='''
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>获取到的数据是:</h1>
    <p>{0}</p>
</body>
</html>
'''.format(value)

print(html)
# index.html中的内容
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>请输入内容</h1>
    <form action="/cgi-bin/cc.py" method="post">
        <select name="sel" >
            <option value="baidu">百度</option>
            <option value="google">谷歌</option>
        </select>
        <input type="submit">
    </form>
</body>
</html>

# cgi程序中的内容
import cgi
import cgitb

cgitb.enable()

print("Content-Type: text/html")
print()

form = cgi.FieldStorage()
value = form.getvalue('sel')

html ='''
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>获取到的数据是:</h1>
    <p>{0}</p>
</body>
</html>
'''.format(value)

print(html)
# 直接访问cgi程序,设置cookie,通过chrome即可查看设置的cookie
# cgi程序为:
import cgi,datetime
import cgitb
from http.cookies import *

cgitb.enable()

name = 'cgicookie'
now = datetime.datetime.utcnow()
time = (now + datetime.timedelta(days=10)).strftime('%a,%d-%m-%Y %H:%M:%S')
path = '/'
domain = '127.0.0.1'
cookie = SimpleCookie()
cookie['NAME'] = name
cookie['NAME']['expires'] = time
cookie['NAME']['path'] = path
cookie['NAME']['domain'] = domain

print("Content-Type: text/html")
print(cookie)
print()

html ='''
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>cookie已经设置</h1>
</body>
</html>
'''

print(html)
# index.html中的内容
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>文件上传</h1>
    <form action="/cgi-bin/cc.py" method="post" enctype="multipart/form-data">
        <p><input type="file" name="upload"></p>
        <p><input type="submit"></p>
    </form>
</body>
</html>

# cgi程序为:
import cgi
import cgitb

cgitb.enable()

form = cgi.FieldStorage()
file = form['upload']
open(file.filename,'wb').write(file.value)

print("Content-Type: text/html")
print()

html ='''
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>已接收上传文件</h1>
</body>
</html>
'''

print(html)
# 直接访问cgi程序,以下为cgi程序的内容
import cgi
import cgitb

cgitb.enable()

data = open(r'chromedriver.exe','rb').read()

print("Content-Disposition: attachment;filename=chromedriver.exe")
print()

print(data)

urlib URL处理模块

使用默认函数访问url

from urllib.request import *

url = 'http://www.baidu.com'
response = urlopen(url)
print(response.read().decode())

使用Request对象构造请求

from urllib.request import *

url = 'http://www.baidu.com'
headers = {
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.84 Safari/537.36',
'Host': 'www.baidu.com'
}
request = Request(url,headers=headers)
response = urlopen(request)
print(response.read().decode())

构造自定的访问器,获取cookie

from urllib.request import *
from http.cookiejar import *

url = 'http://www.baidu.com'
headers = {
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.84 Safari/537.36',
'Host': 'www.baidu.com'
}
cookie = CookieJar()
openr = build_opener(HTTPCookieProcessor(cookie))
request = Request(url,headers=headers)
response = openr.open(request)
print(cookie)
print(response.read().decode())

# 或者

from urllib.request import *
from http.cookiejar import *

url = 'http://www.baidu.com'
headers = {
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.84 Safari/537.36',
'Host': 'www.baidu.com'
}
cookie = CookieJar()
openr = OpenerDirector()
openr.add_handler(HTTPCookieProcessor(cookie))
openr.add_handler(HTTPHandler())
request = Request(url,headers=headers)
response = openr.open(request)
print(cookie)

构造自定访问器,使用用户名、密码登录

from urllib.request import *
from urllib.parse import *

login_url = r'https://www.douban.com/accounts/login'

data = urlencode({
'source': 'index_nav',
'form_email': 'XXXXX',
'form_password': 'XXXXX'
}).encode()

request = Request(url=login_url,data=data)
response = urlopen(request)
print(response.read().decode('utf-8','ignore'))

上一篇 下一篇

猜你喜欢

热点阅读