使用appium实现百度知道自动回答

环境搭建:

1、安装Microsoft.NET.Framework 4.5
2、安装node.js cmd下执行 node
3、安装appium
4、安装ADT工具 (直接在系统变量的path下面将platform-tools加进去) cmd下面执行 adb

5、安装安卓模拟器
6、安装 appium python
(pip install -i https://pypi.tuna.tsinghua.edu.cn/simple --trusted-host pypi.tuna.tsinghua.edu.cn appium-python-Client)
7、需要开启手机 开发者模式及usb调试
8、安装包的包名后缀为apk
9、adb shell dumpsys activity |find “mFocusedActivity” 获取当前活跃前台包名

10、检测当前手机是否连接到电脑 adb devices

11.adt里面的sdk下的tool有uiautomator
12.adb shell dumpsys window w | findstr / | findstr name=

adb shell dumpsys window windows

强烈推荐!!!对应的目录下执行也能获取app的name
D:\android\SDK\build-tools\28.0.3> aapt dump badging d:\test.apk

from selenium.webdriver.support.wait import WebDriverWait
from bs4 import BeautifulSoup
from appium import webdriver
import jieba.analyse
import requests
import string
import time
import re
import eventlet



# 手机的分辨率
phone_w = 1080
phone_h = 2120
# 手机的发送按钮
send_x = 971
send_y = 1866

class appAuto():

    def __init__(self):
        desired_caps = {}
        # 操作系统 -目标机
        desired_caps["platformName"] = "Android"
        # 系统版本
        desired_caps["platformVersion"] = "11"
        # 设备名称
        desired_caps["deviceName"] = "db1a43ef"
        # app信息
        desired_caps["appPackage"] = "com.baidu.iknow"
        # 百度知道 com.baidu.iknow  百度的第一个页面 /com.baidu.iknow.activity.index.IndexActivity
        # 打开app的第一个页面
        desired_caps["appActivity"] = "com.baidu.iknow.activity.common.PrologueActivity"
        # 不进行app重置信息
        desired_caps["noReset"] = "true"
        # 连接appium server,并告诉其要操作的对象
        self.driver = webdriver.Remote('http://127.0.0.1:4723/wd/hub', desired_caps)

    #显性等待
    def wait_a_moment(self,element):
        WebDriverWait(self.driver, 10).until(lambda x: x.find_element_by_android_uiautomator(element))
        time.sleep(0.2)

    #定位tap点击按钮
    def send(self,a,b):
        # print(self.driver.get_window_size())
        a1 =  a/ phone_w
        b1 = b/ phone_h
        # 获取当前手机屏幕大小X,Y
        X = self.driver.get_window_size()['width']
        Y = self.driver.get_window_size()['height']
        # 屏幕坐标乘以系数即为用户要点击位置的具体坐标
        self.driver.tap([(a1 * X, b1 * Y)])
        time.sleep(0.1)

    # 点击发送按钮
    def send_button(self):
        a1 = send_x / phone_w
        b1 = send_y / phone_h
        # 获取当前手机屏幕大小X,Y
        X = self.driver.get_window_size()['width']
        Y = self.driver.get_window_size()['height']
        # 屏幕坐标乘以系数即为用户要点击位置的具体坐标
        self.driver.tap([(a1 * X, b1 * Y)])
        time.sleep(0.3)

    def xiahua(self):
        '''向下滑动屏幕'''
        l = self.driver.get_window_size()  # 获取屏幕尺寸
        # 根据比率来滑动屏幕
        x1 = l['width'] * 0.5  # x坐标
        y1 = l['height'] * 0.25  # 起始y坐标
        y2 = l['height'] * 0.75  # 终点y坐标
        self.driver.swipe(x1, y1, x1, y2)
        # time.sleep(0.1)

    #提取对方问题
    def tiqu_daan(self):
        self.xiahua()
        #这里经常出现没有抢到提的问题
        self.send(621, 938)   #直接抢单
        self.send(621, 1281)  # 直接抢单
        self.send(594, 1427)  # 直接抢单
        # 答题
        # time.sleep(1)  # 进入与用户的页面
        # 提取用户的答案
        # xx = WebDriverWait(self.driver, 10).until(lambda x: x.find_element_by_class_name("android.view.View"))
        # print('定位元素页面',xx)
        self.send(621, 1281)  # 点击页面  看看有激活页面作用没
        self.driver.find_element_by_class_name("android.view.View").click()
        # self.driver.find_element_by_class_name("android.view.View").get_attribute("name")
        rest = self.driver.find_element_by_xpath('//*[contains(@text, "发送")]').get_attribute("name")
        # print(rest)
        # print("提取页面的问题",rest)
        return rest

    def daan(self,r):
        self.wait_a_moment('new UiSelector().text("一起聊聊吧~")')
        self.driver.find_element_by_android_uiautomator('new UiSelector().text("一起聊聊吧~")').click()
        self.driver.find_element_by_android_uiautomator('new UiSelector().text("一起聊聊吧~")').send_keys(r)

    def dati(self):
        try:
            self.tiqu_daan()
        except Exception as e:
            self.tiqu_daan()
        w = str(re.findall(r':\d+(.*)温', self.tiqu_daan())).replace('[', '').replace(']', '').strip(string.punctuation)
        word= jieba.analyse.extract_tags(w, topK=10)
        print("对方的问题" , word)
        # str_space = '祝你好运,祝你好运,祝你好运,祝你好运,祝你好运,祝你好运,祝你好运,祝你好运,祝你好运,祝你好运,祝你好运,祝你好运,祝你好运,祝你好运,祝你好运,祝你好运,祝你好运,祝你好运,祝你好运,祝你好运,祝你好运,祝你好运,祝你好运,,祝你好运'
        # 处理字符串空格和换行
        # strs = "这个问题不是很懂呢,祝你好运基金"
        try:
            strs = self.citiao(word[0]).replace('\n', '').replace(' ', '')
        except Exception as e:
            try:
                strs = self.citiao(word[1]).replace('\n', '').replace(' ', '')
            except Exception as e:
                strs = "这个问题描述的不是很清楚,我没有找到答案,还是祝你好运"
        sta_con = "您好!很高心能为您解答问题!"
        self.daan(sta_con+'\r\n'*7)
        self.send(971, 634)
        self.send(971, 1820)
        self.send_button()
        strp = strs.split("。")
        strp2 = strs.split(",")
        if len(strp) < 4:
            strp=strp2
        for i in strp:
            if len(i) ==0:
                continue
            elif len(i)<=15:
                self.daan(i+'\r\n'*7)
                self.send(971, 634)
                self.send(971,1820)
                self.send_button()
                self.send(971,1945)
            elif len(i)<=30:
                self.daan(i +'\r\n'* 6)
                self.send(971, 634)
                self.send(971,1820)
                self.send_button()
                self.send(971,1945)
            elif len(i) <= 45:
                self.daan(i + '\r\n' * 5)
                self.send(971, 634)
                self.send(971,1820)
                self.send_button()
                self.send(971,1945)
            elif len(i) <= 60:
                self.daan(i + '\r\n' * 4)
                self.send(971, 634)
                self.send(971,1820)
                self.send_button()
                self.send(971,1945)
        #点击x
        self.send(1004, 145)

    #点击在线抢单可能没有单,需要try
    def operation(self):
        # 点击我的
        self.send(400, 400)  # 页面卡住了,随便点击一个空白处,激活页面可以吗
        self.wait_a_moment('new UiSelector().text("我的")')
        self.driver.find_element_by_android_uiautomator('new UiSelector().text("我的")').click()
        # 点击在线聊
        # self.send(743, 2119)
        self.wait_a_moment('new UiSelector().text("在线聊")')
        self.driver.find_element_by_android_uiautomator('new UiSelector().text("在线聊")').click()
        while True:
            self.dati()

    #百度词条
    def citiao(self,word):
        headers = {
            'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
            'Accept-Encoding': 'gzip, deflate, compress',
            'Accept-Language': 'en-us;q=0.5,en;q=0.3',
            'Cache-Control': 'max-age=0',
            'Connection': 'keep-alive',
            'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:22.0) Gecko/20100101 Firefox/22.0'
        }
        url = "https://baike.baidu.com/item/"+word
        r = requests.get(url, headers=headers).text
        soup = BeautifulSoup(r)
        title_node = soup.find('dd', attrs={'class': 'lemmaWgt-lemmaTitle-title'}).find('h1')
        data_want = title_node.getText()
        sum_node = soup.find('div', attrs={'class': 'lemma-summary'})
        data_want = data_want + sum_node.getText()
        # print(data_want.replace('\n', '').replace(' ', ''))
        return data_want

while True:
    try:
        a = appAuto()
        a.operation()
    except Exception as e:
        continue
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值