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

yipeiwu_com5年前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()

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python实现查看系统启动项功能示例

本文实例讲述了Python实现查看系统启动项功能。分享给大家供大家参考,具体如下: 一、代码 # -*- coding:utf-8 -*- #! python3 from win32...

matplotlib绘制动画代码示例

matplotlib从1.1.0版本以后就开始支持绘制动画 下面是几个的示例: 第一个例子使用generator,每隔两秒,就运行函数data_gen: # -*- coding:...

Python数据结构与算法之二叉树结构定义与遍历方法详解

本文实例讲述了Python数据结构与算法之二叉树结构定义与遍历方法。分享给大家供大家参考,具体如下: 先序遍历,中序遍历,后序遍历 ,区别在于三条核心语句的位置 层序遍历  采...

解决python xlrd无法读取excel文件的问题

读取文件时报错: xlrd.biffh.XLRDError: Unsupported format, or corrupt file: Expected BOF record; fo...

Python读取stdin方法实例

Python读取stdin方法实例

Python中常用到的两种标准化输入方式:分别sys.stdin和input,两者使用方式大致相同,但是总的来说sys.stdin使用方式更加多样化一些,下面就例子说明两者之间的使用差别...