通过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实现识别手写MNIST数字集的程序

我们需要做的第⼀件事情是获取 MNIST 数据。如果你是⼀个 git ⽤⼾,那么你能够通过克隆这本书的代码仓库获得数据,实现我们的...

python skimage 连通性区域检测方法

涉及到的函数为 import matplotlib.pyplot as plt from skimage import measure, color labels = measure...

在Python中使用AOP实现Redis缓存示例

越来越觉得的缓存是计算机科学里最NB的发明(没有之一),本文就来介绍了一下在Python中使用AOP实现Redis缓存示例,小伙伴们一起来了解一下 import redis ena...

浅谈python图片处理Image和skimage的区别

浅谈python图片处理Image和skimage的区别

做cnn的难免要做大量的图片处理。由于接手项目时间不长,且是新项目,前段时间写代码都很赶,现在稍微总结(恩,总结是个好习惯)。 1,首先安装python-Image和python-ski...

python实现每次处理一个字符的三种方法

本文实例讲述了python每次处理一个字符的三种方法。分享给大家供大家参考。 具体方法如下: a_string = "abccdea" print 'the first' f...