说明:本文仅供学习参考;请勿用作其他用途

1.功能

已经实现:实现贴吧自动发帖功能(包括标题,内容,上传图片),标题和内容加入了简单的随机字符串,每发一次会随机等待一段时间,关注人数少于50000的不发

缺陷:自动登录需要关闭手机验证,且第一次验证码需要手动拖拽,有想法的同学可以买第三方来做验证码自动识别;发帖间隔不宜过快,否则每次发帖都会要求输入验证码

2.开始编码

以下部分直接上代码,未做较好的封装,有兴趣的朋友自己优化...

# -*- coding: utf-8 -*-

from selenium.webdriver.chrome.options import Options

from selenium import webdriver

from selenium.webdriver.common.keys import Keys

from time import sleep

import logging

import sys

import random

import uuid

from pywinauto import Application

from pywinauto.keyboard import send_keys

logging.basicConfig(level=logging.INFO,

format='%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s', filemode='w',

filename="log.txt")

BROWSER_URL = r'D:\program files (x86)\360chrome\Chrome\Application\360chrome.exe'

from pywinauto.application import Application

class WinAuto:

def __init__(self, class_name, title_re):

# 连接到指定应用程序,此处为连接到指定窗口

self.app = Application().connect(class_name=class_name, title_re=title_re)

# 定位窗口方法

def get_window(self, window_object, class_name="", title_re=""):

return window_object.window(class_name=class_name, title_re=title_re)

# 向编辑框输入指定信息

def file_input(self, file_path):

# 定位到标题名为“打开”对话框

window = self.get_window(self.app, "#32770", "打开")

# 定位到编辑框

window = self.get_window(window, class_name="Edit")

# 向编辑框中输入信息

window.TypeKeys(file_path)

# 点击【打开】按钮

def open_button_click(self):

# 定位到标题名为“打开”对话框

window = self.get_window(self.app, "#32770", "打开")

# 定位到【打开】按钮

button = self.get_window(window, class_name="Button", title_re="打开")

# 点击【打开】按钮

button.click()

def get_titile():

title_list = [

"双十一最强攻略,保证有惊喜,进来了解一下吧",

"双十一撸货套路,来了解一下",

"双11无敌神车已经发车,来了解一下把",

"双11最强攻略,保证你不后悔",

"双十一最强攻略,走过路过不要错过",

]

t = random.choice(title_list)

return t + str(uuid.uuid4()).split('-')[-1]

def get_content():

content = """testest{uuid}atetset{uuid}testest{uuid}test""".format(uuid=str(uuid.uuid4()).split('-')[-1])

return content

def get_datas():

with open('tieba.txt', 'r', encoding='utf-8', errors='ignore') as fp:

schools = fp.readlines()

title = get_titile()

content = get_content()

return title, content, schools

def get_sleep_time(num):

if num % 5 == 0:

t = random.choice(range(180, 300))

else:

t = random.choice(range(35, 125))

logging.info("sleep {}".format(t))

return t

def start_chrome():

chrome_options = Options()

chrome_options.binary_location = BROWSER_URL

# chrome_options.add_argument("–incognito")

driver = webdriver.Chrome(options=chrome_options)

driver.implicitly_wait(20)

if login_tieba(driver):

title, content, schools = get_datas()

num = 0

for name in schools:

url = u"https://tieba.baidu.com/f?ie=utf-8&kw=%s&fr=search" % name

logging.info("start request {}, url:{}".format(name, url))

try:

driver.get(url)

except Exception as e:

logging.error("request {} error".format(name))

continue

followers = driver.find_element_by_class_name("card_menNum").text

logging.info("followers is :{}".format(followers))

followers = followers.replace(',', "")

if int(followers) < 50000:

logging.info("Less than 50000 followers")

continue

try:

driver.find_element_by_xpath("/html/body/ul/li[2]/a").click()

sleep(1)

driver.find_element_by_xpath('//*[@id="tb_rich_poster"]/div[3]/div[1]/div[2]/input').send_keys(title)

# driver.quit()

sleep(1)

driver.find_element_by_id("ueditor_replace").send_keys(content)

sleep(1)

driver.find_element_by_class_name('edui-btn-image').click()

sleep(1)

driver.find_element_by_class_name('pic_upload_container').click()

sleep(1)

driver.find_element_by_class_name('next_step').click()

sleep(1)

# 定位打开窗口

window = WinAuto("#32770", "打开")

sleep(1)

if num % 2 == 0:

window.file_input(r'F:\py_home\selenium_auto\2.jpg')

else:

window.file_input(r'F:\py_home\selenium_auto\3.jpg')

sleep(1)

window.open_button_click()

sleep(8)

driver.find_element_by_link_text('插入图片').click()

sleep(5)

driver.find_element_by_xpath('//*[@id="tb_rich_poster"]/div[3]/div[5]/div/button[1]').click()

except Exception as e:

logging.error("post article failed,: {}".format(e))

import traceback

traceback.print_exc()

continue

num += 1

t = get_sleep_time(num)

sleep(t)

driver.quit()

def login_tieba(driver):

tieba_url = 'https://tieba.baidu.com/'

driver.get(tieba_url)

driver.find_element_by_xpath('//*[@id="com_userbar"]/ul/li[4]/div/a').click()

sleep(2)

try:

driver.find_element_by_xpath('//*[@id="TANGRAM__PSP_11__footerULoginBtn"]').click()

driver.find_element_by_xpath('//*[@id="TANGRAM__PSP_11__userName"]').send_keys('用户名')

driver.find_element_by_xpath('//*[@id="TANGRAM__PSP_11__password"]').send_keys('密码')

driver.find_element_by_xpath('//*[@id="TANGRAM__PSP_11__submitWrapper"]').click()

logging.info("login success")

except Exception:

logging.error("login failed")

sys.exit(1)

logging.info("wait for 10s")

sleep(10)

return True

if __name__ == '__main__':

start_chrome()

用python贴吧自动回帖_python基于selenium实现贴吧自动发帖相关推荐

  1. python携程酒店评论_Python基于selenium爬取携程酒店评论信息

    爬取站点 任意一个携程酒店的详细链接,这里给出了四个,准备开四个线程爬取: https://hotels.ctrip.com/hotel/6278770.html#ctm_ref=hod_hp_hot ...

  2. python模拟拖拽文件_python 基于selenium实现鼠标拖拽功能

    1.准备html文件 首先我们需要准备一个鼠标滑动的html文件,用来演示鼠标滑动的效果,注意需要将我们的html文件放在自己的服务器上, 这样我们才能够通过selenium来进行验证.html文件如 ...

  3. 【Python】基于Selenium实现上海大学校园网自动登录

    [Python]基于Selenium实现上海大学校园网自动登录 安装selenium Selenium官网 以anaconda环境为例,创建一个Selenium的虚拟环境,若不需要可以不做第一.二步 ...

  4. Ubuntu20.04实现Python基于Selenium实现上海大学校园网自动登录

    Ubuntu20.04实现Python基于Selenium实现上海大学校园网自动登录 以anaconda环境为例,创建一个Selenium的虚拟环境: 一.安装selenium 1. conda cr ...

  5. python工业互联网应用实战13—基于selenium的功能测试

    本章节我们再来说说测试,单元测试和功能测试.单元测试我们在数据验证章节简单提过了,本章我们进一步如何用单元测试来测试view的功能代码:同时,也涉及一下基于 selenium 的功能测试做法.笔者过去 ...

  6. 瑞萨L4级自动驾驶方案---基于R-Car V3H SoC的自动驾驶

    全球领先的汽车半导体解决方案供应商瑞萨电子株式会社(TSE:6723)近日宣布,推出新款R-Car V3H片上系统(SoC).该SoC以业界领先的低功耗,为汽车前视摄像头提供强大的计算机视觉性能和人工 ...

  7. python打开摄像头获取图片_Python基于opencv调用摄像头获取个人图片的实现方法

    接触图像领域的应该对于opencv都不会感到陌生,这个应该算是功能十分强劲的一个算法库了,当然了,使用起来也是很方便的,之前使用Windows7的时候出现多该库难以安装成功的情况,现在这个问题就不存在 ...

  8. python中用socket检测端口_python基于socket函数实现端口扫描

    本文实例为大家分享了python基于socket实现端口扫描的具体代码,供大家参考,具体内容如下 自学Python一段时间,写个端口扫描器练练手.有什么不足之处,请见谅 这是基于socket函数对端口 ...

  9. python爬取商品信息_Python基于BeautifulSoup爬取京东商品信息

    今天小编利用美丽的汤来为大家演示一下如何实现京东商品信息的精准匹配~~ HTML文件其实就是由一组尖括号构成的标签组织起来的,每一对尖括号形式一个标签,标签之间存在上下关系,形成标签树:因此可以说Be ...

  10. python 写脚本 预约课程_Python盘纪念币系列之三:自动预约脚本编写 03 系列总结...

    前一篇遗漏了"预约兑换日期"的自动输入,这篇文章将介绍如何处理.另外,将会对"Python盘纪念币系列"做一个简单的总结. 自动输入预约兑换日期 不像文本输入框 ...

最新文章

  1. 如何对linux镜像md5,Linux系统如何校验SHA1和MD5
  2. 如果你不曾失败,只因你从未尝试
  3. python瀑布图怎么做_利用Python绘制数据的瀑布图的教程
  4. Tomcat 7 DBCP 配置(MySQL)
  5. java枚举使用详解
  6. (1) 使用supervisor提高nodejs调试效率
  7. 边缘计算k8s集群之SuperEdge
  8. 太赞了!避免掉坑!佐治亚理工21页优雅读博指南
  9. oracle导入大量csv_Oracle导入数据到表(支持插入大量数据)
  10. 二进制码转十进制java,Java将二进制转换为十进制
  11. 【ElasticSearch】Es 启动流程 源码分析
  12. 如何用sklearn创建机器学习分类器?这里有一份上手指南
  13. 测试sql server服务是否配置正确
  14. 你还在用 Date?快使用 LocalDateTime 了!
  15. 密码库LibTomCrypt学习记录——目录
  16. linux结课考试试题,Linux认证考试课后基础试题及答案
  17. EOF经验正交展开(一)——主成分分析
  18. 论参加数学建模比赛的正确姿势
  19. Hi-C Data Browser:Hi-C数据浏览器
  20. 机器人与视觉,基于坐标系的运动偏移

热门文章

  1. hive整和mysql外表_hive中的外表EXTERNAL TABLE
  2. 面向对象练习:快递柜代码
  3. IP地址和 MAC地址详解
  4. c语言标准库详解(九):实用函数stdlib.h
  5. 基于无线网络的环境监测系统
  6. 【论文精读】Single-Perspective Warps in Natural Image Stitching-自然图像拼接中的单透视扭曲
  7. 网络工程师 第1章 计算机网络概述
  8. 国产银河数学式电子计算机是属于,《世界上公认的第一台电子计算机.doc
  9. Linux 编jpeg函数,JPEG图形库:libjpeg,在LINUX下如何将jpg转换成bmp
  10. linux 软件脱壳机,关于UPX脱壳后程序无法运行