当前位置:主页 > 软件编程 > Python代码 >

通过python3实现投票功能代码实例

时间:2021-01-02 15:14:08 | 栏目:Python代码 | 点击:

这篇文章主要介绍了通过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()

您可能感兴趣的文章:

相关文章