python3网络爬虫开发实战第二版——12 App数据的爬取
配置环境
教程
1 基础设置:抓包工具Charles:(二)Charles的代理设置(windows,app)_闫振兴的博客-CSDN博客_charles设置windows代理
2 证书设置:抓包工具Charles:(三)https协议的抓取_闫振兴的博客-CSDN博客
参考:Charles安装与配置
配套视频:软件测试教程Charles抓包工具测试实战_哔哩哔哩_bilibili
Charles 抓包都是unknown
在Charles配置的过程中,忘记允许SSL了
SSL的端口是443
(还有一点就是app传输加密了,而charles不会自动解密的)
GitHub
安装后 控制台输入 mitmdump 报错
ModuleNotFoundError: No module named ‘_cffi_backend’
运行以下命令
pip -vvv install --upgrade --force-reinstall cffi
GitHub
安装配置环境比较麻烦
参考:Appium 的安装 | 静觅
环境变量配置参考:Android Studio 和 SDK 环境变量配置_siwuxie095’s blog-CSDN博客
参考:Android Studio: Gradle/Maven配置国内镜像源_gaocui883的博客-CSDN博客_android gradle 国内镜像
Appium Inspector
参考:appium 1.22.0版本 Appium Inspector 连接使用教程_达文西先生的博客-CSDN博客_appium inspector
Appium Inspector 下载
参考:Appium Inspector使用_BUG1314的专栏-CSDN博客_appium inspector
{
"platformName": "Android",
"deviceName": "RMX2117",
"appPackage": "com.goldze.mvvmhabit",
"appActivity": ".ui.MainActivity",
"noRest": true
}
参考:【Appium踩坑】Permission denial: writing to settings requires:android.permission.WRITE_SECURE_SETTINGS_青禾tester-CSDN博客_开发者选项里禁止权限监控
设置 - 更多设置 - 开发者选项 - USB调试(安全设置)- 开启
*OPPO设备: 开启 禁止权限监控
开发者选项 - 禁止权限监控 - 开启
然后会要安装几个应用程序
el2 = driver.find_element_by_xpath("/hierarchy/android.widget.FrameLayout/android.widget.LinearLayout/android.widget.FrameLayout/android.widget.LinearLayout/android.widget.FrameLayout/android.widget.FrameLayout/android.widget.LinearLayout/android.widget.RelativeLayout/android.support.v7.widget.RecyclerView/android.widget.LinearLayout[4]/android.widget.LinearLayout/android.widget.TextView[1]")
el2.click()
Python操作app
GitHub
from appium import webdriver # pip install Appium-Python-Client
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
server = 'http://localhost:4723/wd/hub'
desired_capabilities = {
"platformName": "Android",
"deviceName": "RMX2117", # 你的手机model号
"appPackage": "com.goldze.mvvmhabit",
"appActivity": ".ui.MainActivity",
"noReset": True
}
driver = webdriver.Remote(server, desired_capabilities)
wait = WebDriverWait(driver, 30)
wait.until(EC.presence_of_all_elements_located(
(By.XPATH, '//android.support.v7.widget.RecyclerView/android.widget.LinearLayout')))
window_size = driver.get_window_size()
width, height = window_size.get('width'), window_size.get('height')
driver.swipe(width * 0.5, height * 0.8, width * 0.5, height * 0.2, 1000) # 滑动
GitHub
import json
import os
from appium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
from selenium.common.exceptions import NoSuchElementException
from loguru import logger
SERVER = 'http://localhost:4723/wd/hub'
DESIRED_CAPABILITIES = {
"platformName": "Android",
"deviceName": "RMX2117",
"appPackage": "com.goldze.mvvmhabit",
"appActivity": ".ui.MainActivity",
"noReset": True
}
PACKAGE_NAME = DESIRED_CAPABILITIES['appPackage'] # 包名 为后续编写获取节点的逻辑做准备的
TOTAL_NUMBER = 100 # 电影条目总共有100条
driver = webdriver.Remote(SERVER, DESIRED_CAPABILITIES)
wait = WebDriverWait(driver, 30)
window_size = driver.get_window_size() # 获取屏幕大小
window_width, window_height = window_size.get(
'width'), window_size.get('height')
"""
点击电影条目节点
进入详情页后爬取信息
点击回退按钮返回首页
"""
def scrape_detail(element):
logger.debug(f'scraping {element}')
element.click()
wait.until(EC.presence_of_element_located(
(By.ID, f'{PACKAGE_NAME}:id/detail')))
title = wait.until(EC.presence_of_element_located(
(By.ID, f'{PACKAGE_NAME}:id/title'))).get_attribute('text')
categories = wait.until(EC.presence_of_element_located(
(By.ID, f'{PACKAGE_NAME}:id/categories_value'))).get_attribute('text')
score = wait.until(EC.presence_of_element_located(
(By.ID, f'{PACKAGE_NAME}:id/score_value'))).get_attribute('text')
minute = wait.until(EC.presence_of_element_located(
(By.ID, f'{PACKAGE_NAME}:id/minute_value'))).get_attribute('text')
published_at = wait.until(EC.presence_of_element_located(
(By.ID, f'{PACKAGE_NAME}:id/published_at_value'))).get_attribute('text')
drama = wait.until(EC.presence_of_element_located(
(By.ID, f'{PACKAGE_NAME}:id/drama_value'))).get_attribute('text')
driver.back()
return {
'title': title,
'categories': categories,
'score': score,
'minute': minute,
'published_at': published_at,
'drama': drama
}
# 先爬取首页的所有电影条目 返回一个列表
def scrape_index():
items = wait.until(EC.presence_of_all_elements_located(
(By.XPATH, f'//android.widget.LinearLayout[@resource-id="{PACKAGE_NAME}:id/item"]')))
return items
scraped_titles = []
OUTPUT_FOLDER = 'movie'
os.path.exists(OUTPUT_FOLDER) or os.makedirs(OUTPUT_FOLDER)
def save_data(element_data):
with open(f'{OUTPUT_FOLDER}/{element_data.get("title")}.json', 'w', encoding='utf-8') as f:
f.write(json.dumps(element_data, ensure_ascii=False, indent=2))
logger.debug(f'saved as file {element_data.get("title")}.json')
def get_element_title(element):
try:
element_title = element.find_element_by_id(
f'{PACKAGE_NAME}:id/tv_title').get_attribute('text')
return element_title
except NoSuchElementException:
return None
def scroll_up():
driver.swipe(window_width * 0.5, window_height * 0.8,
window_width * 0.5, window_height * 0.5, 1000)
def main():
while len(scraped_titles) < TOTAL_NUMBER:
elements = scrape_index()
for element in elements:
element_title = get_element_title(element)
if not element_title or element_title in scraped_titles:
continue
element_location = element.location
element_y = element_location.get('y')
if element_y / window_height > 0.8: # 当爬取的节点对于的电影条目差不多是页面高度的80%时
logger.debug(f'scroll up')
scroll_up() # 页面上划
element_data = scrape_detail(element)
scraped_titles.append(element_title) # 全局变量scraped_titles 用于去重
logger.debug(f'scraped data {element_data}')
save_data(element_data)
if __name__ == '__main__':
main()
2021-12-29 20:05:56.274 | DEBUG | __main__:scrape_detail:36 - scraping <appium.webdriver.webelement.WebElement (session="fa372f83-aba8-4721-a51b-f96abdfa0a33", element="00000000-0000-2a0a-ffff-ffff00000019")>
2021-12-29 20:06:00.072 | DEBUG | __main__:main:110 - scraped data {'title': '霸王别姬', 'categories': '剧情、爱情', 'score': '9.5', 'minute': '171分钟', 'published_at': '1993-07-26', 'drama': '影片借一出《霸王别姬》的京戏,牵扯出三个人之间一段随时代风云变幻的爱恨情仇。段小楼(张丰毅 饰)与程蝶衣(张国荣 饰)是一对打小一起长大的师兄弟,两人一个演生,一个饰旦,一向配合天衣无缝,尤其一出《霸王别姬》,更是誉满京城,为此,两人约定合演一辈子《霸王别姬》。但两人对戏剧与人生关系的理解有本质不同,段小楼深知戏非人生,程蝶衣则是人戏不分。段小楼在认为该成家立业之时迎娶了名妓菊仙(巩俐 饰),致使程蝶衣认定菊仙是可耻的第三者,使段小楼做了叛徒,自此,三人围绕一出《霸王别姬》生出的爱恨情仇战开始随着时代风云的变迁不断升级,终酿成悲剧。'}
2021-12-29 20:06:00.073 | DEBUG | __main__:save_data:79 - saved as file 霸王别姬.json
2021-12-29 20:06:01.363 | DEBUG | __main__:scrape_detail:36 - scraping <appium.webdriver.webelement.WebElement (session="fa372f83-aba8-4721-a51b-f96abdfa0a33", element="00000000-0000-2a0a-ffff-ffff0000001f")>