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

yipeiwu_com6年前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 django 增删改查操作 数据库Mysql

下面介绍一下django增删改查操作: 1、view.py # -*- coding: utf-8 -*- from __future__ import unicode_litera...

VScode编写第一个Python程序HelloWorld步骤

VScode编写第一个Python程序HelloWorld步骤

一、软件下载与安装 VScode下载地址:https://code.visualstudio.com/ VScode的github项目地址(本文用不到):https://github....

Django如何防止定时任务并发浅析

前言 django提供了commands类,允许我们编写命令行脚本,并且可以通过python manage.py拉起。 了解commands 具体django commands如何使用...

python通过opencv实现批量剪切图片

上一篇文章中,我们介绍了python实现图片处理和特征提取详解,这里我们再来看看Python通过OpenCV实现批量剪切图片,具体如下。 做图像处理需要大批量的修改图片尺寸来做训练样本,...

详解将Django部署到Centos7全攻略

详解将Django部署到Centos7全攻略

Django部署到Cenos7需要安装大量的依赖包, 有很多坑需要踩, 这里是踩坑后探索出的标准化步骤 实验环境: 腾讯云centos7 用centos7.5镜像创建容器(这步操作按自己...