Python urllib + http.cookiejar


img

  • 中文文档
    urllib.request
    urllib.parse
    http.cookiejar

模拟登陆J站

import urllib.request
import urllib.parse
import http.cookiejar as cookiejar


# 声明一个CookieJar对象实例来保存cookie
jar = cookiejar.CookieJar()

# 利用urllib库的HTTPCookieProcessor对象来创建cookie处理器(BaseHandler 子类)
handler=urllib.request.HTTPCookieProcessor(jar)

# 返回一个 openerDirector 实例。handler 可以是 BaseHandler 的实例,也可以是 BaseHandler 的子类
opener = urllib.request.build_opener(handler)

# 安装 OpenerDirector 实例作为默认全局启动器
urllib.request.install_opener(opener)


url = "http://www.jdlingyu.mobi/wp-admin/admin-ajax.php?action=zrz_ajax_login"
data = {'name':'',
        'pass':'密码',
        'phoneEmail': '用户名',
        'code':'',
        'security':'8d7a489047'}

header = {'User-Agent':'Mozilla/5.0 (X11; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0'}

rawdata = urllib.parse.urlencode(data).encode('utf-8')
req = urllib.request.Request(url, data=rawdata, headers=header)
rsp = urllib.request.urlopen(req)

print(rsp.read().decode("utf-8"))

def text():
    url = "http://www.jdlingyu.mobi/user/48720/collection-post/" 
    req = urllib.request.Request(url, headers=header)
    rsp = urllib.request.urlopen(req)
    print(rsp.read().decode('utf-8'))


text()

结果

你可能感兴趣的:(Python urllib + http.cookiejar)