Python3 投票

import urllib.request
# cd C:\Python36-32\Scripts
# pip install BeautifulSoup
from bs4 import BeautifulSoup


def vote(get_url, post_url, option):
    # 访问投票页面,拿到cookie
    resp = urllib.request.urlopen(get_url)
    cookie = resp.getheader('Set-Cookie')
    # print(cookie)

    # 读取response信息
    html = resp.read()
    # HTML解析器,拿到vote_option
    bs = BeautifulSoup(html, "html.parser")
    # 后台校验的动态验证码,随自己业务调整
    secret_key = bs.find('input', id='secret_key').get("value")
    # print(vote_option)

    # hearders部分,cookie等
    headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.12; rv:52.0) Gecko/20100101 Firefox/52.0',
               'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
               'Cookie': cookie}

    # post提交的数据,第一个为选中的复选框选项(多个中间逗号分隔),第二个为动态码(后台校验)
    data_json = {'option': option, 'secret_key': secret_key}
    # string转为byte类型,因为客户端校验要求
    data = urllib.parse.urlencode(data_json).encode("utf-8")
    # post请求,提交投票数据
    req = urllib.request.Request(post_url, headers=headers, data=data)
    response = urllib.request.urlopen(req)
    # 查看返回结果,转码为中文
    print(bytes.decode(response.read()))


def deal():
    # get连接、post链接、选项 根据自己业务修改
    get_url = ""
    post_url = ""
    option = ""
    vote(get_url, post_url, option)


deal()

 

posted @ 2019-09-26 10:56  大飞90  阅读(496)  评论(0编辑  收藏  举报