NO.15——使用Appium自动化测试爬取微信朋友圈数据
                                                            生活随笔
收集整理的這篇文章主要介紹了
                                NO.15——使用Appium自动化测试爬取微信朋友圈数据
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.                        
                                ? ? ?一、解析過程
本人使用錘子手機做測試,型號是YQ601,首先打開開發者模式確保手機能與mac相連,打開Appium客戶端,配置參數如圖
可以理解為Appuim繼承自web端的selenium,同樣可以執行一些自動化操作。Appium自帶了一個XPATH選擇器,給用戶提供了選擇結果,如圖
這個選擇器給出的結果太繁瑣,所以可以改成通過查找ID的方式來構造爬蟲程序。但是這里要注意,估計微信提升了自己的反爬能力,在測試時發現,每次重新連接手機,對應特定節點的ID都會發生變化,保險起見,每次重新連接手機,都要對節點ID作更新。
? ? ? ?這里把程序分為三部分:(1)模擬登陸(2)進入朋友圈(3)抓取動態(4)存入數據庫
二、代碼
import os from appium import webdriver from appium.webdriver.common.touch_action import TouchAction from selenium.common.exceptions import NoSuchElementException from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from pymongo import MongoClient from time import sleep from processor import Processor from config import *class Moments():def __init__(self):"""初始化"""# 驅動配置self.desired_caps = {'platformName': PLATFORM,'deviceName': DEVICE_NAME,'appPackage': APP_PACKAGE,'appActivity': APP_ACTIVITY}self.driver = webdriver.Remote(DRIVER_SERVER, self.desired_caps)self.wait = WebDriverWait(self.driver, TIMEOUT)self.client = MongoClient(MONGO_URL)self.db = self.client[MONGO_DB]self.collection = self.db[MONGO_COLLECTION]# 處理器self.processor = Processor()def login(self):"""登錄微信:return:"""# 登錄按鈕login = self.wait.until(EC.presence_of_element_located((By.ID, 'com.tencent.mm:id/d75')))login.click()# 手機輸入phone = self.wait.until(EC.presence_of_element_located((By.ID, 'com.tencent.mm:id/hz')))phone.set_text(USERNAME)# 下一步next = self.wait.until(EC.element_to_be_clickable((By.ID, 'com.tencent.mm:id/alr')))next.click()# 密碼password = self.wait.until(EC.presence_of_element_located((By.XPATH, '//*[@resource-id="com.tencent.mm:id/hz"][1]')))password.set_text(PASSWORD)# 提交submit = self.wait.until(EC.element_to_be_clickable((By.ID, 'com.tencent.mm:id/alr')))submit.click()# 是否查看通訊錄yesORnot = self.wait.until(EC.element_to_be_clickable((By.ID, 'com.tencent.mm:id/an2')))yesORnot.click()def enter(self):"""進入朋友圈:return:"""# 選項卡tab = self.wait.until(EC.presence_of_element_located((By.XPATH, '//*[@resource-id="com.tencent.mm:id/b0w"][3]')))tab.click()# 朋友圈moments = self.wait.until(EC.presence_of_element_located((By.ID, 'com.tencent.mm:id/a7f')))moments.click()def crawl(self):"""爬取:return:"""while True:# 當前頁面顯示的所有狀態items = self.wait.until(EC.presence_of_all_elements_located((By.XPATH, '//*[@resource-id="com.tencent.mm:id/d58"]//android.widget.FrameLayout')))# 上滑self.driver.swipe(FLICK_START_X, FLICK_START_Y + FLICK_DISTANCE, FLICK_START_X, FLICK_START_Y)# 遍歷每條狀態for item in items:try:# 昵稱nickname = item.find_element_by_id('com.tencent.mm:id/as6').get_attribute('text')# 正文content = item.find_element_by_id('com.tencent.mm:id/ib').get_attribute('text')# 日期date = item.find_element_by_id('com.tencent.mm:id/dfw').get_attribute('text')# 處理日期date = self.processor.date(date)print(nickname, content, date)data = {'nickname': nickname,'content': content,'date': date,}# 插入MongoDBself.collection.update({'nickname': nickname, 'content': content}, {'$set': data}, True)sleep(SCROLL_SLEEP_TIME)except NoSuchElementException:passdef main(self):"""入口:return:"""# 登錄self.login()# 進入朋友圈self.enter()# 爬取self.crawl()if __name__ == '__main__':moments = Moments()moments.main() import time import reclass Processor():def date(self, datetime):"""處理時間,轉化成發布時間的時間戳:param datetime: 原始時間:return: 處理后時間"""if re.match('\d+分鐘前', datetime):minute = re.match('(\d+)', datetime).group(1)datetime = time.strftime('%Y-%m-%d', time.localtime(time.time() - float(minute) * 60))if re.match('\d+小時前', datetime):hour = re.match('(\d+)', datetime).group(1)datetime = time.strftime('%Y-%m-%d', time.localtime(time.time() - float(hour) * 60 * 60))if re.match('昨天', datetime):datetime = time.strftime('%Y-%m-%d', time.localtime(time.time() - 24 * 60 * 60))if re.match('\d+天前', datetime):day = re.match('(\d+)', datetime).group(1)datetime = time.strftime('%Y-%m-%d', time.localtime(time.time()) - float(day) * 24 * 60 * 60)return datetime總結
以上是生活随笔為你收集整理的NO.15——使用Appium自动化测试爬取微信朋友圈数据的全部內容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: HC32F460 FPU使用
- 下一篇: 一篇关于保险与公积金的文章,看了绝对受益
