| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115 |
- import requests
- import base64
- import cv2
- import uiautomator2 as u2
- import time
- import subprocess
- import re
- import random
- import datetime
- import json
- from apscheduler.schedulers.blocking import BlockingScheduler
- from aip import AipOcr
- import numpy as np
- import cv2
- import os
- from pdd_config import Config
- import logging
- from logger import setup_logger
- import xml.etree.ElementTree as ET
- import secrets
- import secrets
- import urllib.parse
- import oss2
- # versionName=7.96.0 只适用CMKFUSSG99ROR489
- setup_logger("pdd_spider") # 初始化日志
- def get_access_token():
- AppKey = "tRK2RhyItCSh6BzyT4CNVXQa"
- AppSrcret = "TDgKiPo94i2mOM1sDqOuDnlcK1bG66jh"
- token_url = 'https://aip.baidubce.com/oauth/2.0/token'
- url = f"{token_url}?grant_type=client_credentials&client_id={AppKey}&client_secret={AppSrcret}"
- payload = ""
- headers = {
- 'Content-Type': 'application/json',
- 'Accept': 'application/json'
- }
- response = requests.request("POST", url, headers=headers, data=payload)
- try:
- return response.json()['access_token']
- except:
- return None
- def get_mysql():
- """
- 建立并返回一个到数据库的连接对象
- """
- import pymysql
- return pymysql.connect(
- host = Config.DB_HOST, #"localhost", # 修改后的主机
- port = Config.DB_PORT, #3306, # 添加端口号
- user = Config.DB_USER, #'root', # 修改后的用户名
- password = Config.DB_PASSWORD, # 修改后的密码
- db = Config.DB_NAME, #"drug_data", # 修改后的数据库名
- charset='utf8mb4'
- )
- #获取滑块验证中滑块需要移动的距离
- def slide_verify(img_path):
- with open(img_path, 'rb') as f:
- b = base64.b64encode(f.read()).decode() ## 图片二进制流base64字符串
- url = "http://api.jfbym.com/api/YmServer/customApi"
- data = {
- ## 关于参数,一般来说有3个;不同类型id可能有不同的参数个数和参数名,找客服获取
- "token": "1nDVocTE2mJ0yLEYb2sZJ5uUY2VIEoGTkIpW44X7Kgk",
- "type": "22222",
- "image": b,
- }
- _headers = {
- "Content-Type": "application/json"
- }
- response = requests.request("POST", url, headers=_headers, json=data).json()
- print(response)
- if response.get("msg") == "识别成功":
- # 获取 data 中的 data 字段
- result = response.get("data", {}).get("data")
- if result:
- print(result) # 输出结果
- else:
- print("无法获取数据")
- else:
- print("识别未成功")
- return result
- class PDD:
- def __init__(self, search_key, device_id):
- self.package_name = 'com.xunmeng.pinduoduo'
- self.APP_ID = '116857964'
- self.API_KEY = Config.API_KEY
- self.SECRET_KEY = Config.SECRET_KEY
- self.client = AipOcr(self.APP_ID, self.API_KEY, self.SECRET_KEY)
- # self.city2province = self.get_city_info()
- # host = "localhost"
- # user = "root"
- # password = "dfwy2025"
- # database = "drug_data"
- # port = 3306
- # self.table_name = "mt_drug"
- self.table_name = Config.DB_PDD_TABLE #"pdd_drug"
- self.shop_table_name = Config.DB_PDD_SHOP_TABLE #"pdd_shop_info"
- self.loggerPdd = logging.getLogger()
- self.clipboard = "" #初始化剪切板的内容为空
- self.access_token = get_access_token()
- self.search_key = search_key # 参苓健脾胃颗粒 香砂平胃颗粒 舒肝颗粒 清肺化痰丸
- self.unrelated_data = 0 # 无关数据数量
- self.device_id = device_id
- #统计售罄数量
- self.sold_out_counts = 0
- #最大量数据阈值
- self.max_counts = 5
- #统计点击商品的次数
- self.click_counts = 0
- #程序启动时间
- self.program_start_time = self.app_start_time()
- # oss配置
- self.oss_config = {
- "access_key_id": Config.access_key_id,
- "access_key_secret": Config.access_key_secret,
- "endpoint": Config.endpoint, # 例: oss-cn-beijing.aliyuncs.com
- "bucket_name": Config.bucket_name,
- "oss_prefix": Config.oss_prefix # OSS中存放截图的前缀(虚拟文件夹)
- }
- # OSS配置与初始化(核心配置,无冗余)
- # self.oss_bucket = self._init_oss_bucket()
- # 代码运行那时候的时间
- def app_current_time(self):
- return datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
- def app_start_time(self):
- """
- 获取app启动时间
- :return:
- """
- return datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
- def stop_app(self):
- self.d.app_stop(self.package_name)
- time.sleep(5)
- def start_app(self):
- self.d.app_start(self.package_name)
- time.sleep(5)
- def restart_app(self):
- """
- 重启app
- :return:
- """
- self.stop_app()
- self.start_app()
- @staticmethod
- def get_sleep_time():
- return random.randint(1, 3)
- # return random.randint(5, 8)
- @staticmethod
- def get_current_date():
- return datetime.datetime.now().strftime('%Y/%m/%d')
- @staticmethod
- def get_city_info():
- """
- 获取所有的省市数据
- :return:
- """
- file_path = '../kailin_city.json'
- with open(file_path, 'r', encoding='utf-8') as f:
- data = json.load(f)
- province = {province_one["id"]: province_one for province_one in data['province']}
- city2province = dict()
- city = data['city']
- for city_one in city:
- name = city_one['name']
- pid = city_one['pid']
- if len(str(pid)) > 2:
- pid = int(re.match(r'^\d{2}', str(pid)).group())
- city2province[name] = province[pid]['name']
- return city2province
- def remove_watermark(self, img_path):
- """
- 图片去水印(将水印部分变成白色背景)并将数据转化为二进制数据
- :param img_path: 图片路径
- :return: 二进制图片数据
- """
- img = cv2.imdecode(np.fromfile(img_path, dtype=np.uint8), -1)
- endswith = os.path.splitext(img_path)[1]
- new = np.clip(1.4057577998008846 * img - 38.33089999653017, 0, 255).astype(np.uint8)
- _, img_binary = cv2.imencode(endswith, new)
- return img_binary
- def human_slide(self,start_x, start_y, end_x, end_y):
- """模拟人类滑动轨迹"""
- # 生成带加速度的轨迹
- points = []
- total_steps = 50
- distance_x = end_x - start_x
- distance_y = end_y - start_y
- previous_x = start_x # 用于记录上一个 x 坐标值
- for i in range(total_steps):
- # 非线性进度(慢-快-慢)
- ratio = (i / total_steps)
- if ratio < 0.3:
- progress = 0.5 * (ratio / 0.3)**2
- elif ratio < 0.7:
- progress = 0.5 + (ratio - 0.3) * 1.25
- else:
- progress = 0.9 + 0.5 * ((ratio - 0.7)/0.3)**0.5
- # 添加随机抖动
- # offset_x = np.random.randint(-2, 3)
- # offset_y = np.random.randint(-2, 3)
- offset_x = np.random.randint(-1, 1) # 控制抖动范围
- offset_y = np.random.randint(-1, 1)
- x = start_x + distance_x * min(progress, 0.99) + offset_x
- y = start_y + distance_y * min(progress, 0.99) + offset_y
- # 确保 x 坐标单调递增
- if x < previous_x and x < end_x:
- x = previous_x + 1
- if x > end_x:
- x = end_x
- previous_x = x
- points.append((x, y))
- # 变速延迟(移动越快延迟越短)
- delay = 0.002 + 0.01 * (1 - abs(0.5 - ratio))
- time.sleep(delay)
- print(f"points: {points}")
- self.loggerPdd.info(f"points: {points}")
- # 执行滑动轨迹
- # self.d.touch.down(points[0][0], points[0][1])
- for point in points[1:]:
- self.d.touch.move(point[0], point[1])
- self.d.touch.up(points[-1][0], points[-1][1])
- # print(f"points: {points}")
- # self.loggerPdd.info(f"points: {points}")
- # self.d.swipe_points(points, duration=0.05)
- def get_shop_name(self):
- """
- 获取店铺名
- :return:
- """
- try:
- xpath = '//*[@text="进店"]/preceding-sibling::android.view.ViewGroup/android.widget.LinearLayout/android.widget.TextView'
- if self.d.xpath(xpath).exists:
- shop_name = self.d.xpath(xpath).text
- self.loggerPdd.info(f'1-获取到店铺名:{shop_name}')
- else:
- #进入店铺新页面
- shop_btn_xpath = '//*[@resource-id="android:id/content"]/android.widget.FrameLayout[1]/android.widget.LinearLayout[1]/android.widget.LinearLayout[1]/android.widget.LinearLayout[1]/android.widget.LinearLayout[1]'
- if self.d.xpath(shop_btn_xpath).exists:
- self.d.xpath(shop_btn_xpath).click()
- time.sleep(1)
- # self.d.xpath('//*[@text="店铺"]').click()
- xpath_shop_name = '//*[@resource-id="android:id/content"]/android.widget.FrameLayout[1]/android.view.ViewGroup[1]/android.widget.LinearLayout[1]/android.widget.RelativeLayout[1]/android.widget.LinearLayout[1]/android.support.v7.widget.RecyclerView[1]/android.widget.RelativeLayout[1]/android.view.ViewGroup[1]/android.widget.LinearLayout[1]/android.widget.LinearLayout[1]/android.widget.LinearLayout[1]/android.widget.LinearLayout[1]/android.widget.TextView[1]'
- if self.d.xpath(xpath_shop_name).exists:
- shop_name = self.d.xpath(xpath_shop_name).text
- self.loggerPdd.info(f'2-获取到店铺名:{shop_name}')
- else:
- shop_name = ''
- self.loggerPdd.info(f'3-获取到店铺名:{shop_name}')
- self.swipe_back(1) #
- else:
- shop_name = ''
- self.loggerPdd.info('4-因为shop_btn_xpath不存在,获取到店铺名为空')
- # time.sleep(10000)
- #进入店铺新页面 测试代码
- # self.d.xpath('//*[@text="店铺"]').click()
- # time.sleep(1)
- # content_frame = self.d.xpath('//*[@resource-id="android:id/content"]/android.widget.FrameLayout[1]').exists
- # print(content_frame)
- # ViewGroup3 = self.d.xpath('//*[@resource-id="android:id/content"]/android.widget.FrameLayout[1]/android.view.ViewGroup[1]').exists
- # print(ViewGroup3)
- # LinearLayout = self.d.xpath('//*[@resource-id="android:id/content"]/android.widget.FrameLayout[1]/android.view.ViewGroup[1]/android.widget.LinearLayout[1]').exists
- # print(LinearLayout)
- # RelativeLayout = self.d.xpath('//*[@resource-id="android:id/content"]/android.widget.FrameLayout[1]/android.view.ViewGroup[1]/android.widget.LinearLayout[1]/android.widget.RelativeLayout[1]').exists
- # print(RelativeLayout)
- # LinearLayout2 = self.d.xpath('//*[@resource-id="android:id/content"]/android.widget.FrameLayout[1]/android.view.ViewGroup[1]/android.widget.LinearLayout[1]/android.widget.RelativeLayout[1]/android.widget.LinearLayout[1]').exists
- # print(LinearLayout2)
- # RecyclerView = self.d.xpath('//*[@resource-id="android:id/content"]/android.widget.FrameLayout[1]/android.view.ViewGroup[1]/android.widget.LinearLayout[1]/android.widget.RelativeLayout[1]/android.widget.LinearLayout[1]/android.support.v7.widget.RecyclerView[1]').exists
- # print(RecyclerView)
- # xpath2 = '//*[@resource-id="android:id/content"]/android.widget.FrameLayout[1]/android.view.ViewGroup[1]/android.widget.LinearLayout[1]/android.widget.RelativeLayout[1]/android.widget.LinearLayout[1]/android.support.v7.widget.RecyclerView[1]/android.widget.RelativeLayout[1]/android.view.ViewGroup[1]/android.widget.LinearLayout[1]/android.widget.LinearLayout[1]/android.widget.LinearLayout[1]/android.widget.LinearLayout[1]/android.widget.TextView[1]'
- # if self.d.xpath(xpath2).exists:
- # shop_name = self.d.xpath(xpath2).text
- # self.loggerPdd.info(f'2-获取到店铺名:{shop_name}')
- # else:
- # shop_name = ''
- # self.loggerPdd.info(f'3-获取到店铺名:{shop_name}')
- # self.swipe_back(1) #返回
- return shop_name
- except Exception as e:
- print(f'获取店铺名出错:{e}')
- self.loggerPdd.error(f'获取店铺名出错:{e}')
- return None
- def get_qualification_number(self):
- """
- 获取资质编号
- :return:
- """
- try:
- qualification_number_str = self.d.xpath(
- '//*[@resource-id="com.sankuai.meituan:id/mil_container"]/android.webkit.WebView[1]/android.webkit.WebView[1]/android.view.View[1]/android.view.View[1]/android.widget.TextView[2]').text
- qualification_number = qualification_number_str.strip('资质编号:').strip()
- return qualification_number
- except:
- return None
- def enter_detail(self):
- self.d.xpath('//*[@resource-id="com.sankuai.meituan:id/recycler"]/android.widget.FrameLayout[1]').click()
- time.sleep(self.get_sleep_time())
- def save_to_database(self, data):
- print(f'保存数据到数据库:{data}')
- # 连接数据库
- conn = get_mysql()
- # 创建游标对象
- cur = conn.cursor()
- # add_sql = "insert into delete_friend_table(delete_user_name,delete_user_id,delete_content,delete_time) value(%s,%s,%s,%s)"
- add_sql = f"""
- INSERT INTO {self.table_name}
- (product, min_price, manufacture_date, expiry_date, shop, business_license_company, province, city, manufacturer, specification, approval_number, product_link, scrape_date, scrape_province, availability, credit_code, platform, search_key, number)
- VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
- """
- # cur.execute(add_sql, (data['product'], data['min_price'], data['manufacture_date'], data['expiry_date'], data['shop'], data['business_license_company'],data['province'], data['city'], data['manufacturer'], data['specification'], data['approval_number'], data['product_link'], self.get_current_date(), data['scrape_province'], data['availability'], data['credit_code'], data['platform']))
- cur.execute(add_sql, (data['product'], data['min_price'], data['manufacture_date'], data['expiry_date'], data['shop'], data['business_license_company'],data['province'], data['city'], data['manufacturer'], data['specification'], data['approval_number'], data['product_link'], data['scrape_date'], data['scrape_province'], data['availability'], data['credit_code'], data['platform'], data['search_key'], data['number']))
- conn.commit() # 提交数据
- print(f"存入数据库成功")
- def click_target_product_by_search_key(self, fuzzy_match=False, timeout=10):
- """
- 动态匹配self.search_key对应的商品并点击
- :param fuzzy_match: 是否模糊匹配(应对商品名带额外后缀/前缀的情况) 不模糊匹配
- :param timeout: 等待元素出现的超时时间(秒)
- :return: 点击是否成功(bool)
- """
- try:
- # 1. 定义定位条件(动态使用self.search_key)
- if fuzzy_match:
- # 模糊匹配:包含search_key即可(推荐,适配搜索结果商品名略有差异)
- locator = self.d(textContains=self.search_key)
- print(f"🔍 模糊匹配商品:包含「{self.search_key}」的元素")
- else:
- # 精确匹配:商品名与search_key完全一致
- locator = self.d(text=self.search_key)
- print(f"🔍 精确匹配商品:「{self.search_key}」")
- # 2. 等待元素出现(核心:避免元素未加载就点击)
- if locator.wait(timeout=timeout):
- print(f"✅ 找到匹配的商品,准备点击")
- # 执行点击(优先点击可点击的元素)
- locator.click()
- print(f"✅ 成功点击「{self.search_key}」对应的商品")
- # 点击后等待页面加载
- time.sleep(self.get_sleep_time())
- return True
- else:
- # print(f"❌ 超时未找到「{self.search_key}」对应的商品,尝试滑动刷新")
- # # 容错:向上滑动(加载更多)后重试
- # self.swipe_up()
- # 滑动后再等待5秒重试
- # if locator.wait(timeout=5):
- # locator.click()
- # print(f"✅ 滑动后找到并点击「{self.search_key}」对应的商品")
- # return True
- # else:
- print(f"❌ 滑动后仍未找到「{self.search_key}」对应的商品")
- return False
- except Exception as e:
- print(f"❌ 点击「{self.search_key}」对应商品时异常:{e}")
- return False
- def swipe_down(self):
- """
- 下滑(模拟真人操作,抗风控+设备适配+容错)
- 核心:起点在屏幕上方,终点在屏幕下方(和上滑相反)
- :return: None
- """
- try:
- # 1. 获取屏幕尺寸(兼容不同设备,给默认值避免获取失败)
- screen_width = self.d.info.get('displayWidth', 1080) # 默认1080px宽度
- screen_height = self.d.info.get('displayHeight', 2400) # 默认2400px高度
- # 2. 随机滑动时长(0.1~0.3秒,避免固定值被风控,且不设0秒)
- duration_rate = random.uniform(0.1, 0.3)
- # 3. 计算滑动坐标(用屏幕比例,适配所有设备)
- start_x = screen_width // 2 # 水平居中(和上滑一致,符合真人操作习惯)
- start_y = screen_height * 0.2 # 起点:屏幕20%高度(上方偏下)
- end_y = screen_height * 0.8 # 终点:屏幕80%高度(下方偏上)
- # 强制确保起点y < 终点y(必为向下滑,避免逻辑错误)
- start_y, end_y = min(start_y, end_y - 10), max(end_y, start_y + 10)
- # 4. 核心向下滑动操作
- self.d.swipe(start_x, start_y, start_x, end_y, duration=duration_rate)
- # 滑动后全局等待(确保页面加载,避免元素定位失败)
- time.sleep(self.get_sleep_time())
- except Exception as e:
- # 异常捕获:避免设备断开/滑动失败导致程序崩溃
- print(f"向下滑动失败:{e}")
- # 兜底方案:用固定坐标重试(适配主流1080x2400设备)
- self.d.swipe(540, 480, 540, 1920, duration=0.2)
- time.sleep(self.get_sleep_time())
- def swipe_up(self):
- """
- 上滑
- :return:
- """
- screen_width = self.d.info['displayWidth']
- screen_height = self.d.info['displayHeight']
- duration_rate = random.uniform(0, 0.3)
- self.d.swipe(screen_width // 2, screen_height - 100, screen_width // 2, 100, duration=duration_rate)
- no = random.uniform(0, 1)
- if no > 0.85:
- # 有的时候卡着 再稍微往上滑一点点
- self.d.swipe_ext("up", 0.1)
- time.sleep(self.get_sleep_time())
- def swipe_back(self, no):
- """
- 返回
- :param no: 回退次数
- :return:
- """
- if not self.distinct_target():
- for idx in range(no):
- self.d.press('back')
- time.sleep(self.get_sleep_time())
- def drug_price(self):
- """
- 获取药品价格
- :return:
- """
- try:
- xpath = '//*[@text="¥"]/following-sibling::android.widget.TextView[1]'
- price_str = self.d.xpath(xpath).text
- price = float(re.search(r'[\d\.]+', price_str).group())
- print(f'获取到价格:{price}')
- return float(price)
- except Exception as e:
- print(f'提取价格出错-->{e}')
- return None
- def drug_price_ex(self):
- price_str = '' #价格初始化
- ext = '' #初始化已选择的信息
- price = ''
- button_xpath_1 = '//*[@resource-id="android:id/content"]/android.widget.FrameLayout[1]/android.widget.LinearLayout[1]/android.widget.LinearLayout[1]/android.widget.LinearLayout[2]/android.widget.LinearLayout[1]/android.widget.LinearLayout[1]/android.view.ViewGroup[last()]'
- button_xpath_2 = '//*[@resource-id="android:id/content"]/android.widget.FrameLayout[1]/android.widget.LinearLayout[1]/android.widget.LinearLayout[1]/android.widget.LinearLayout[2]/android.widget.LinearLayout[1]/android.widget.LinearLayout[1]/android.widget.LinearLayout[1]/android.view.ViewGroup[last()]'
- button_xpath_3 = '//*[@resource-id="android:id/content"]/android.widget.FrameLayout[1]/android.widget.LinearLayout[1]/android.widget.LinearLayout[1]/android.widget.LinearLayout[2]/android.widget.LinearLayout[1]/android.widget.LinearLayout[1]/android.view.ViewGroup[2]'
- button_xpath_4 = '//*[@resource-id="android:id/content"]/android.widget.FrameLayout[1]/android.widget.LinearLayout[1]/android.widget.LinearLayout[1]/android.widget.LinearLayout[2]/android.widget.LinearLayout[1]/android.view.ViewGroup[1]/android.widget.ImageView[1]'
- button_xpath_5 = '//*[@resource-id="android:id/content"]/android.widget.FrameLayout[1]/android.widget.LinearLayout[1]/android.widget.LinearLayout[1]/android.widget.LinearLayout[2]/android.widget.LinearLayout[1]/android.view.ViewGroup[last()]'
- #调试
- # test_button = self.d.xpath(button_xpath_1).exists
- # print(test_button)
- # test_button_2 = self.d.xpath(button_xpath_2).exists
- # print(test_button_2)
- # time.sleep(1000)
- # if self.d.xpath('//*[@text="发起拼单"]').exists:
- # self.d.xpath('//*[@text="发起拼单"]').click()
- # elif self.d.xpath('//*[@text="去复诊开药"]').exists:
- # self.d.xpath('//*[@text="去复诊开药"]').click()
- if self.d.xpath(button_xpath_1).exists:
- self.d.xpath(button_xpath_1).click()
- elif self.d.xpath(button_xpath_2).exists:
- self.d.xpath(button_xpath_2).click()
- elif self.d.xpath(button_xpath_3).exists:
- self.d.xpath(button_xpath_3).click()
- elif self.d.xpath(button_xpath_4).exists:
- self.d.xpath(button_xpath_4).click()
- elif self.d.xpath(button_xpath_5).exists:
- self.d.xpath(button_xpath_5).click()
- else:
- print("button1 and button_2 and button_3 and button_4 and button_5 all not exist")
- return price, ext
- #获取是已选择还是请选择
- # select_xpath = '//*[@resource-id="android:id/content"]/android.widget.RelativeLayout[1]/android.widget.FrameLayout[1]/android.widget.RelativeLayout[1]/android.widget.RelativeLayout[1]/android.widget.TextView[2]'
- select_xpath_1 = '//*[@resource-id="android:id/content"]/android.widget.RelativeLayout[1]/android.widget.FrameLayout[1]/android.widget.RelativeLayout[1]/android.widget.TextView[last()]'
- select_xpath_2 = '//*[@resource-id="android:id/content"]/android.widget.RelativeLayout[1]/android.widget.FrameLayout[1]/android.widget.RelativeLayout[1]/android.widget.RelativeLayout[1]/android.widget.TextView[last()]'
- select_xpath_3 = '//*[@resource-id="android:id/content"]/android.widget.FrameLayout[1]/android.widget.LinearLayout[1]/android.view.ViewGroup[2]/android.widget.LinearLayout[1]/android.view.ViewGroup[1]/android.widget.LinearLayout[1]/android.widget.FrameLayout[1]/android.widget.RelativeLayout[1]/android.view.ViewGroup[1]/android.widget.TextView[last()]'
- select_xpath_3_2 = '//*[@resource-id="android:id/content"]/android.widget.FrameLayout[1]/android.widget.LinearLayout[1]/android.view.ViewGroup[2]/android.widget.LinearLayout[1]/android.view.ViewGroup[1]/android.widget.LinearLayout[1]/android.widget.FrameLayout[1]/android.widget.RelativeLayout[1]/android.view.ViewGroup[1]/android.widget.TextView[last()-1]'
- # select_xpath1 = self.d.xpath(select_xpath_1).exists
- # print(select_xpath1)
- # select_xpath2 = self.d.xpath(select_xpath_2).exists
- # print(select_xpath2)
- # select_xpath3 = self.d.xpath(select_xpath_3).exists
- # print(select_xpath3)
- # time.sleep(1000)
- price_xpath_1 = '//*[@resource-id="android:id/content"]/android.widget.RelativeLayout[1]/android.widget.FrameLayout[1]/android.widget.RelativeLayout[1]/android.widget.TextView[1]'
- price_xpath_2 = '//*[@resource-id="android:id/content"]/android.widget.RelativeLayout[1]/android.widget.FrameLayout[1]/android.widget.RelativeLayout[1]/android.widget.RelativeLayout[1]/android.widget.TextView[1]'
- price_xpath_3 = '//*[@resource-id="android:id/content"]/android.widget.FrameLayout[1]/android.widget.LinearLayout[1]/android.view.ViewGroup[2]/android.widget.LinearLayout[1]/android.view.ViewGroup[1]/android.widget.LinearLayout[1]/android.widget.FrameLayout[1]/android.widget.RelativeLayout[1]/android.view.ViewGroup[1]//android.widget.TextView[1]'
- if self.d.xpath(select_xpath_1).exists:
- text1 = self.d.xpath(select_xpath_1).text
- print(f"select_xpath_1--text1={text1}")
- if '已选' in text1:
- if self.d.xpath(price_xpath_1).exists:
- price_str = self.d.xpath(price_xpath_1).text
- print(f"select_xpath_1--price_str-1={price_str}")
- else:
- print("select_xpath_1--price_xpath_1-1 not exist")
- ext = text1
- elif '请选择' in text1:
- #需要再下面点击选择
- scroll_xpath_1 = '//*[@resource-id="android:id/content"]//android.widget.ScrollView[1]/android.widget.LinearLayout[1]/android.support.v7.widget.RecyclerView[1]/android.widget.LinearLayout[last()]/android.view.ViewGroup[1]/android.view.ViewGroup[last()]'
- if self.d.xpath(scroll_xpath_1).exists:
- self.d.xpath(scroll_xpath_1).click
- time.sleep(2) #延时2秒钟,选择了之后价格会刷新
- if self.d.xpath(select_xpath_1).exists:
- text2 = self.d.xpath(select_xpath_1).text
- if '已选' in text2:
- print(f"select_xpath_1--已选择2:text2={text2}")
- if self.d.xpath(price_xpath_1).exists:
- price_str = self.d.xpath(price_xpath_1).text
- print(f"select_xpath_1--price_str-2={price_str}")
- else:
- print("select_xpath_1--price_xpath_1-2 not exist")
- ext = text2
- else:
- print("select_xpath_1--scroll_xpath_1 not exist")
- elif self.d.xpath(select_xpath_2).exists:
- text1 = self.d.xpath(select_xpath_2).text
- print(f"xpath2--text1={text1}")
- if '已选' in text1:
- ext = text1
- if self.d.xpath(price_xpath_2).exists:
- price_str = self.d.xpath(price_xpath_2).text
- print(f"select_xpath_2--price_str-2={price_str}")
- else:
- print("select_xpath_2--price_xpath_2-1 not exist")
- elif '请选择' in text1:
- print('come in here')
- #需要再下面点击选择
- scroll_xpath_1 = '//*[@resource-id="android:id/content"]//android.widget.ScrollView[1]/android.widget.LinearLayout[1]/android.support.v7.widget.RecyclerView[1]/android.widget.LinearLayout[last()]/android.view.ViewGroup[1]/android.view.ViewGroup[1]'
- if self.d.xpath(scroll_xpath_1).exists:
- print("scroll_xpath_1 exists")
- self.d.xpath(scroll_xpath_1).click()
- time.sleep(2) #延时2秒钟,选择了之后价格可能会刷新
- if self.d.xpath(select_xpath_2).exists:
- text2 = self.d.xpath(select_xpath_2).text
- if '已选' in text2:
- ext = text2
- print(f"select_xpath_2--已选择2:text2={text2}")
- if self.d.xpath(price_xpath_2).exists:
- price_str = self.d.xpath(price_xpath_2).text
- print(f"select_xpath_2--price_str-2={price_str}")
- else:
- print("select_xpath_2--price_xpath_2-2 not exist")
- else:
- print("scroll_xpath_1 not exists")
- else:
- print("not exist 请选择 or 已选")
- elif self.d.xpath(select_xpath_3).exists:
- text1 = self.d.xpath(select_xpath_3).text
- print(f"xpath3--text1-1={text1}")
- if ('请选择' not in text1) and ('已选' not in text1):
- text1 = self.d.xpath(select_xpath_3_2).text
- print(f"xpath3--text1-2={text1}")
- if '已选' in text1:
- ext = text1
- if self.d.xpath(price_xpath_3).exists:
- price_str = self.d.xpath(price_xpath_3).text
- print(f"select_xpath_3--price_str-3-3-1={price_str}")
- else:
- print("select_xpath_3--price_xpath_3-3-1 not exist")
- elif '请选择' in text1:
- print('come in here')
- #需要再下面点击选择
- scroll_xpath_1 = '//*[@resource-id="android:id/content"]//android.widget.ScrollView[1]/android.widget.LinearLayout[1]/android.support.v7.widget.RecyclerView[1]/android.widget.LinearLayout[last()]/android.view.ViewGroup[1]/android.view.ViewGroup[1]'
- recycler_view_xpath = '//*[@resource-id="android:id/content"]//android.support.v7.widget.RecyclerView[1]/android.widget.LinearLayout[1]/android.widget.LinearLayout[last()]/android.view.ViewGroup[1]/android.view.ViewGroup[1]'
- if self.d.xpath(scroll_xpath_1).exists:
- print("scroll_xpath_1 exists")
- self.d.xpath(scroll_xpath_1).click()
- time.sleep(2) #延时2秒钟,选择了之后价格可能会刷新
- if self.d.xpath(select_xpath_3).exists:
- text2 = self.d.xpath(select_xpath_3).text
- if '已选' in text2:
- ext = text2
- print(f"select_xpath_3--已选择2:text2={text2}")
- if self.d.xpath(price_xpath_3).exists:
- price_str = self.d.xpath(price_xpath_3).text
- print(f"select_xpath_3--price_str-3-2={price_str}")
- else:
- print("select_xpath_3--price_xpath_3-3-2 not exist")
- elif self.d.xpath(recycler_view_xpath).exists:
- self.d.xpath(recycler_view_xpath).click()
- time.sleep(2) #延时2秒钟,选择了之后价格可能会刷新
- if self.d.xpath(select_xpath_3).exists:
- text2 = self.d.xpath(select_xpath_3).text
- if '已选' in text2:
- ext = text2
- print(f"select_xpath_3--已选择2:text2={text2}")
- if self.d.xpath(price_xpath_3).exists:
- price_str = self.d.xpath(price_xpath_3).text
- print(f"select_xpath_3--price_str-3-3={price_str}")
- else:
- print("select_xpath_3--price_xpath_3-3-3 not exist")
- else:
- print("scroll_xpath_1 not exists")
- else :
- print(f"xpath3--text1-不包含请选择和已选择")
- else :
- print("select_xpath_1 and select_xpath_2 and select_xpath_3 all not exist")
- if price_str:
- # price = float(re.search('[\d\.]+', price_str).group())
- match = re.search(r'¥([\d\.]+)', price_str)
- if match:
- price = float(match.group(1))
- else:
- price = ''
- # price = float(re.search(r'¥([\d\.]+)', price_str).group(1))
- print(f'获取到价格:{price}')
- print(f"ext={ext}")
- self.swipe_back(1) #
- # time.sleep(1000)
- return price, ext
- def restart_uiautomator_services(self, device_id):
- """
- 重启atx的uiautomator 服务
- :param device_id:
- :return:
- """
- stop_uiautomator_services = f'adb -s {device_id} shell /data/local/tmp/atx-agent server -d --stop'
- start_uiautomator_services = f'adb -s {device_id} shell /data/local/tmp/atx-agent server -d'
- # result = subprocess.run(stop_uiautomator_services, capture_output=True, text=True, shell=True)
- # print(result.stdout)
- subprocess.run(stop_uiautomator_services, capture_output=True, text=True, shell=True)
- time.sleep(self.get_sleep_time())
- subprocess.run(start_uiautomator_services, capture_output=True, text=True, shell=True)
- time.sleep(self.get_sleep_time())
- def connect_devices(self, device_id):
- """
- 连接设备
- :return:
- """
- try:
- self.d = u2.connect_usb(device_id)
- # 设置隐形等待时间
- # self.d.implicitly_wait(5)
- self.restart_uiautomator_services(device_id)
- print(f'[{self.program_start_time}]连接到设备:{device_id}')
- except Exception as e:
- print(f'{device_id} 连接错误: {e}')
- raise Exception(e)
- def get_ocr_res(self, img):
- try:
- image = self.remove_watermark(img)
- # image_file = open(img,'wb')
- # image_file.write(image)
- # res_image = self.client.basicAccurate(image) # 高精度
- res_image = self.client.basicGeneral(image)
- # print(f'百度api返回结果:{res_image}')
- # print(res_image.get('words_result', ''))
- # new_dic = dict()
- data = res_image.get('words_result', '')
- print(f'百度api返回结果:{data}')
- # full_text = ';'.join(item['words'] for item in data)
- # address = ''
- # for item in data:
- # if '企业注册号' in item['words']:
- # print('come in 111')
- # reg_number = item['words'].split(':', 1)[1].strip()
- # elif '企业名称' in item['words']:
- # print('come in 222')
- # company_name = item['words'].split(':', 1)[1].strip()
- # elif '所:' in item['words']:
- # print('come in 333')
- # address = item['words'].split(':', 1)[1].strip()
- # # 输出结果
- # print("企业注册号:", reg_number)
- # print("企业名称:", company_name)
- # print("住所:", address)
- return data
- except:
- return None
- # def get_ocr_res(self, img):
- # try:
- # #img地址
- # print(f'开始识别图片:{img}')
- # request_url = "https://aip.baidubce.com/rest/2.0/ocr/v1/business_license"
- # # 二进制方式打开图片文件
- # f = open(img, 'rb')
- # img = base64.b64encode(f.read())
- # # img = self.remove_watermark(img)
- # # print(f'图片转base64成功:{img}')
- # params = {"image": img}
- # # access_token = get_access_token()
- # request_url = request_url + "?access_token=" + self.access_token
- # headers = {'content-type': 'application/x-www-form-urlencoded'}
- # response = requests.post(request_url, data=params, headers=headers)
- # print(f'请求百度api成功{response}')
- # if response:
- # res = response.json()
- # print(f'百度api返回结果{res}')
- # new_dic = dict()
- # for ite in res['words_result'].keys():
- # new_dic[ite] = res['words_result'][ite]['words']
- # print('资质数据信息', new_dic)
- # return new_dic
- # else:
- # return None
- # except:
- # return None
- def screenshot_the_business_license(self):
- screenshot_path = 'screenshot1.png'
- self.d.screenshot(screenshot_path)
- img = cv2.imread(screenshot_path)
- # 指定裁剪区域 (left, top, right, bottom)
- left = 0
- top = 480
- right = 720
- bottom = 1420
- cropped_img = img[top:bottom, left:right]
- cropped_screenshot_path = 'cropped_screenshot.png'
- cv2.imwrite(cropped_screenshot_path, cropped_img)
- def screenshot_the_shop_qualifications(self):
- screenshot_path = 'screenshot2.png'
- self.d.screenshot(screenshot_path)
- img = cv2.imread(screenshot_path)
- # 指定裁剪区域 (left, top, right, bottom)
- left = 0
- top = 480
- right = 720
- bottom = 1420
- def first_screenshot_the_verify(self):
- screenshot_verify_path = 'first_screenshot_verify.png'
- self.d.screenshot(screenshot_verify_path)
- img = cv2.imread(screenshot_verify_path)
- ocr_res = self.get_ocr_res('first_screenshot_verify.png')
- event = '' #事件类型:滑块验证、计算结果输入
- if ocr_res:
- for item in ocr_res:
- if '拖动滑块完成' in item['words']:
- print("滑块验证")
- event = '滑块验证'
- break
- # 指定裁剪区域 (left, top, right, bottom)
- if event == '滑块验证':
- left = 118
- top = 478
- right = 602
- bottom = 722
- else:
- left = 118
- top = 478
- right = 602
- bottom = 722
- cropped_verify_img = img[top:bottom, left:right]
- cropped_verify_creenshot_path = 'first_cropped_verify_screenshot.png'
- cv2.imwrite(cropped_verify_creenshot_path, cropped_verify_img)
- return event
- def slide_second_screenshot_the_verify(self):
- screenshot_verify_path = 'slide_second_screenshot_verify.png'
- self.d.screenshot(screenshot_verify_path)
- img = cv2.imread(screenshot_verify_path)
- left = 118
- top = 478
- right = 602
- bottom = 722
- cropped_verify_img = img[top:bottom, left:right]
- cropped_verify_creenshot_path = 'second_slide_cropped_verify_screenshot.png'
- cv2.imwrite(cropped_verify_creenshot_path, cropped_verify_img)
- def second_screenshot_the_verify(self):
- screenshot_verify_path = 'second_screenshot_verify.png'
- self.d.screenshot(screenshot_verify_path)
- img = cv2.imread(screenshot_verify_path)
- ocr_res = self.get_ocr_res('second_screenshot_verify.png')
- print(f'second_ocr_res:{ocr_res}')
- result = ''
- if ocr_res:
- result = '验证成功'
- for item in ocr_res:
- if '验证成功' in item['words']:
- result = '验证成功'
- break
- elif '验证不成功' in item['words']:
- result = '验证不成功'
- break
- return result
- def screenshot_business_license(self,shop_name):
- screenshot_lincense_path = 'license_screenshot.png'
- self.d.screenshot(screenshot_lincense_path)
- img = cv2.imread(screenshot_lincense_path)
- #裁剪
- left = 0
- top = 160
- right = 720
- bottom = 1000
- cropped_verify_img = img[top:bottom, left:right]
- cropped_screenshot_path = 'D:\\work\\dfwy_spider\\drug_data\\pdd\\screenshot\\' + shop_name + '.png'
- cv2.imwrite(cropped_screenshot_path, cropped_verify_img)
- return cropped_screenshot_path
- def drug_slide(self, distance):
- print(f"滑动的distance= {distance}")
- # 获取设备上所有窗口的层次结构
- dump = self.d.dump_hierarchy()
- print(f"drug_slide-111:{dump}")
- # 解析 JSON 数据
- root = ET.fromstring(dump)
- # dump_data = json.loads(dump)
- print("drug_slide-222")
- # 查找包含 meco.webkit.WebView 的元素
- webview_elements = root.findall(".//node[@class='meco.webkit.WebView']")
- print("drug_slide-333")
- if webview_elements:
- print("找到 WebView 元素:", webview_elements[0].attrib)
- # 获取WebView的bounds信息
- webview_bounds = webview_elements[0].attrib['bounds']
- print("WebView bounds:", webview_bounds)
- # 假设你需要操作的元素在WebView中的XPath为'//node[@class="meco.webkit.WebView"]'
- webview_element_xpath = '//node[@class="meco.webkit.WebView"]'
- # 获取WebView内部元素
- webview_inner_elements = self.d.xpath(webview_element_xpath)
- if webview_inner_elements:
- # 拖动元素300像素
- start_x = webview_inner_elements[0].info['bounds'][0]
- start_y = webview_inner_elements[0].info['bounds'][1]
- end_x = start_x + distance
- end_y = start_y
- self.d.swipe(start_x, start_y, end_x, end_y)
- print("拖动成功")
- else:
- print("未找到需要拖动的元素")
- else:
- print("未找到 WebView 元素")
- def get_title(self):
- try:
- print('开始提取标题')
- time.sleep(self.get_sleep_time())
- title_xpath = '//*[@resource-id="com.xunmeng.pinduoduo:id/tv_title"]'
- if self.d.xpath(title_xpath).exists:
- title = self.d.xpath(title_xpath).info['contentDescription'].strip()
- else:
- return None
- # title = self.d.xpath('//*[@resource-id="com.xunmeng.pinduoduo:id/tv_title"]').info['contentDescription'].strip()
- print(f'提取到标题:{title}')
- return title
- except Exception as e:
- print(f'获取标题出错:{e}')
- return None
- # 从里面匹配出药品名和规格
- # drugs_name
- # specifications
- # match = re.search(r'([^\d]+)([\d\D]+)', title)
- # match = re.search(r'(\[[^\]]+\])(.+?)(\d+.*)', title)
- # if match:
- # drugs_name = match.group(1).strip() + match.group(2).strip()
- # specifications = match.group(3).strip()
- # print("药品名:", drugs_name)
- # print("规格:", specifications)
- # print('完整药名:', drugs_name + specifications)
- # return drugs_name, specifications
- # else:
- # print("没有匹配到预期格式")
- def enter_shop(self):
- """
- 进店,方便提取资质环境
- :return:
- """
- # self.d.xpath('//*[@text="进店"]').click()
- self.d.xpath('//*[@text="店铺"]').click()
- time.sleep(self.get_sleep_time())
- def enter_shoper(self):
- """
- 进入商家
- :return:
- """
- self.d.xpath('//*[@text="商家"]').click()
- time.sleep(self.get_sleep_time())
- def scan_shoper_license(self):
- self.d.xpath('//*[@text="查看商家资质"]').click()
- time.sleep(self.get_sleep_time())
- def data_is_exists(self, data):
- # 1. 验证必要字段
- required_keys = ['search_key', 'min_price', 'shop', 'scrape_date', 'platform']
- if not all(key in data for key in required_keys):
- missing = [key for key in required_keys if key not in data]
- # logging.error(f"缺少必要字段: {', '.join(missing)}")
- print(f"缺少必要字段: {', '.join(missing)}")
- return None
- try:
- # 连接数据库
- conn = get_mysql()
- # 创建游标对象
- cur = conn.cursor()
- # query_sql = f"SELECT * FROM {self.table_name} WHERE product = '{data['product']}' AND min_price = '{data['min_price']}' AND shop = '{data['shop']}' AND scrape_date = '{data['scrape_date']}' AND platform = '{data['platform']}'"
- # cur.execute(query_sql)
- query_sql = """
- SELECT * FROM {}
- WHERE search_key = %s
- AND min_price = %s
- AND shop = %s
- AND scrape_date = %s
- AND platform = %s
- """.format(self.table_name)
- cur.execute(query_sql, (
- data['search_key'],
- data['min_price'],
- data['shop'],
- data['scrape_date'],
- data['platform']
- ))
- result = cur.fetchone()
- return bool(result) # 如果存在返回True,否则False
- except Exception as e:
- print(f"MySQL 错误: {str(e)}")
- #验证店铺信息是否在数据库中已存在
- def shop_is_exists_database(self, shop):
- try:
- # 连接数据库
- conn = get_mysql()
- # 创建游标对象
- cur = conn.cursor()
- query_sql = """
- SELECT * FROM {}
- WHERE shop = %s
- """.format(self.shop_table_name)
- cur.execute(query_sql, (
- shop
- ))
- result = cur.fetchone()
- return bool(result) # 如果存在返回True,否则False
- except Exception as e:
- print(f"MySQL 错误: {str(e)}")
- def get_instructions_data(self):
- """
- 确定有详情页之后之后,提取所有的详情页数据
- :return:
- """
- #下面的for循环已经有滑动的操作了,不要一进来就滑动。
- # self.d.swipe_ext("up", scale=0.5)
- for i in range(8):
- # if self.d(textStartsWith="查看全部").exists:
- if self.d.xpath('//*[@text="品牌"]').exists or self.d.xpath('//*[@text="药品通用名"]').exists:
- self.d.swipe_ext("up", scale=0.1)
- print('开始采集详情数据')
- break
- # screen_width = self.d.info['displayWidth']
- # screen_height = self.d.info['displayHeight']
- # self.d.swipe(screen_width // 2, screen_height - 400, screen_width // 2, 400, duration=0.2)
- self.d.swipe_ext("up", scale=0.5)
- time.sleep(self.get_sleep_time())
- # 点击查看全部
- if self.d.xpath('//*[@text="品牌"]').exists:
- self.d.xpath('//*[@text="品牌"]').click()
- else:
- self.d.xpath('//*[@text="药品通用名"]').click()
- time.sleep(self.get_sleep_time())
- attr = dict()
- # # 获取详情页信息
- xpath = '//*[starts-with(@text,"商品参数")]/parent::*/parent::*/following-sibling::*/*/*/android.view.ViewGroup//android.widget.TextView'
- ddd = self.d.xpath(xpath).all()
- for i in range(0, len(ddd), 2):
- group = ddd[i:i + 2]
- attr[group[0].text] = group[1].text
- # 截图获取未获取到的数据
- # if not all(i in ['有效期', '生产企业', '批准文号', '药品规格', '产品规格'] for i in attr.keys()):
- if not all(i in ['有效期', '生产企业', '批准文号', '药品规格'] for i in attr.keys()):
- self.d.swipe_ext("up", 0.4)
- time.sleep(self.get_sleep_time())
- xpath = '//*[starts-with(@text,"商品参数")]/parent::*/parent::*/following-sibling::*/*/*/android.view.ViewGroup//android.widget.TextView'
- ddd = self.d.xpath(xpath).all()
- for i in range(0, len(ddd), 2):
- group = ddd[i:i + 2]
- attr[group[0].text] = group[1].text
- print(f'当前说明书规格参数:{attr}')
- res_data = {
- # "有效期": attr.get('有效期',''),
- # "生产单位": attr['生产企业'],
- # "批准文号": attr['批准文号'],
- # "产品规格": attr.get('药品规格') if attr.get('药品规格', '') else attr.get('药品规格')
- "有效期": attr.get('有效期',''),
- "生产单位": attr.get('生产企业', ''),
- "批准文号": attr.get('批准文号', ''),
- "产品规格": attr.get('药品规格', '')
- }
- print(f'当前规格参数字典数据:{res_data}')
- return res_data
- def has_instructions(self):
- """
- 是否有详情页
- :return:如果有详情页返回True,否则返回False
- """
- # 没有说明书的无法采集具体数据
- max_attempts = 12 # 最大尝试次数
- attempt = 0 # 当前尝试次数
- while attempt < max_attempts:
- time.sleep(0.5)
- xpath = '//*[@text="商品详情"]'
- is_has_instructions = self.d.xpath(xpath).exists
- if is_has_instructions:
- return True # 如果找到“商品详情”,则返回True
- self.d.swipe_ext("up", 0.3)
- attempt += 1
- return False # 如果尝试次数达到最大次数,则返回False
- # time.sleep(self.get_sleep_time())
- # xpath = '//*[@text="商品详情"]'
- # is_has_instructions = self.d.xpath(xpath).exists
- # return
- def has_shop_qualifications(self):
- max_attempts = 3 # 最大尝试次数
- attempt = 0 # 当前尝试次数
- while attempt < max_attempts:
- time.sleep(0.5)
- xpath = '//*[@text="查看全部"]'
- is_has_search_all = self.d.xpath(xpath).exists
- if is_has_search_all:
- elements = self.d.xpath(xpath).all()
- count = len(elements)
- print(f"页面上共有 {count} 个 '查看全部' 元素")
- if count >= 2:
- second_element = elements[1]
- bounds = second_element.bounds
- else:
- element = self.d.xpath(xpath).get()
- bounds = element.bounds
- print(f'bounds:{bounds}')
- # time.sleep(1000000)
- # 获取元素的坐标和尺寸
- x1, y1, x2, y2 = bounds # x1, y1 是左上角坐标,x2, y2 是右下角坐标
- element_x = (x1 + x2) / 2 # 元素的中心 x 坐标
- element_y = (y1 + y2) / 2 # 元素的中心 y 坐标
- if element_y > 500:
- self.d.swipe(element_x, element_y, element_x, 500, 1)
- #画完之后再去一次坐标
- elements_ex = self.d.xpath(xpath).all()
- count_ex = len(elements_ex)
- print(f"第二次页面上共有 {count_ex} 个 '查看全部' 元素")
- if count_ex >= 2:
- second_element_ex = elements[1]
- bounds_ex = second_element_ex.bounds
- else:
- element_ex = self.d.xpath(xpath).get()
- bounds_ex = element_ex.bounds
- print(f'bounds_ex:{bounds_ex}')
- x1, y1, x2, y2 = bounds_ex # x1, y1 是左上角坐标,x2, y2 是右下角坐标
- element_x = (x1 + x2) / 2 # 元素的中心 x 坐标
- element_y = (y1 + y2) / 2 # 元素的中心 y 坐标
- time.sleep(self.get_sleep_time())
- target_x = element_x
- target_y = element_y + 80
- print(f'目标坐标:{target_x}, {target_y}')
- #点击图片
- self.d.click(target_x, target_y)
- time.sleep(self.get_sleep_time())
- #获取图片内容
- self.screenshot_the_shop_qualifications()
- ocr_res = self.get_ocr_res('screenshot2.png')
- print(f'ocr_res:{ocr_res}')
- time.sleep(100000)
- return True # 如果找到“商品详情”,则返回True
- self.d.swipe_ext("up", 0.1)
- attempt += 1
- return False # 如果尝试次数达到最大次数,则返回False
- def get_license_info_ex(self, shop_name):
- # print('开始获取商家资质信息')
- self.enter_shop() #点击店铺
- #点击店铺图片
- xpath_shop_image = '//*[@resource-id="android:id/content"]/android.widget.FrameLayout[1]/android.view.ViewGroup[1]/android.widget.LinearLayout[1]/android.widget.RelativeLayout[1]/android.widget.LinearLayout[1]/android.support.v7.widget.RecyclerView[1]/android.widget.RelativeLayout[1]/android.view.ViewGroup[1]/android.widget.LinearLayout[1]/android.widget.LinearLayout[1]/android.widget.ImageView[1]'
- if self.d.xpath(xpath_shop_image).exists:
- self.d.xpath(xpath_shop_image).click()
- time.sleep(self.get_sleep_time())
- #从弹窗页获取店铺资质的位置
- for i in range(10):
- if self.d.xpath('//*[@text="店铺资质"]').exists:
- print('店铺资质存在1')
- break
- self.d.swipe_ext('up', 0.3)
- time.sleep(1)
- if self.d.xpath('//*[@text="店铺资质"]').exists:
- print('店铺资质存在2')
- break
- if self.d.xpath('//*[@text="已上传"]').exists:
- self.d.xpath('//*[@text="已上传"]').click()
- else:
- self.d.xpath('//*[@text="店铺资质"]').click()
- time.sleep(self.get_sleep_time())
- xpath_pop_window = '//*[@resource-id="android:id/content"]/android.widget.FrameLayout[1]/android.widget.FrameLayout[1]/android.widget.FrameLayout[1]/android.view.ViewGroup[1]/android.widget.FrameLayout[1]/android.widget.FrameLayout[1]/meco.webkit.WebView[1]'
- #等待验证弹窗出现
- for i in range(10):
- if self.d.xpath(xpath_pop_window).exists:
- print(f'第{i}次安全验证弹窗存在')
- break
- else:
- print(f'第{i}次安全验证弹窗不存在')
- time.sleep(self.get_sleep_time())
- time.sleep(10)
- #第一次截屏
- event = self.first_screenshot_the_verify()
- #用ocr的方式识别当前是拖动还是点击
- # ocr_res = self.get_ocr_res('screenshot_verify.png')
- # event = ''
- # if ocr_res:
- # for item in ocr_res:
- # if '拖动滑块完成' in item['words']:
- # print("滑块验证")
- # event = '滑块验证'
- # break
- # print("ocr_res end")
- if event == '滑块验证':
- #需要点击》按钮不懂后截屏,获取
- self.d.touch.down(110, 780)
- time.sleep(0.5)
- #截屏
- event = self.slide_second_screenshot_the_verify()
- # result = slide_verify('first_cropped_verify_screenshot.png') second_slide_cropped_verify_screenshot
- result = slide_verify('second_slide_cropped_verify_screenshot.png')
- result = int(result)
- print(f'滑动距离:{result}')
- print('开始滑动')
- # internel = 1000
- # self.d.touch.move_to(110 + result, 780, duration=internel)
- # self.d.touch.up(110 + result, 780)
- self.human_slide(110, 780, 110 + result, 780)
- print('滑动结束')
- time.sleep(self.get_sleep_time())
- #滑完之后怎么判断是否验证成功?
- second_resut = self.second_screenshot_the_verify()
- if second_resut == '验证成功':
- time.sleep(8)
- cropped_screenshot_path = self.screenshot_business_license(shop_name)
- ocr_res = self.get_ocr_res(cropped_screenshot_path)
- print(f'ocr_res:{ocr_res}')
- company_name = ''
- reg_number = ''
- address = ''
- if ocr_res:
- for item in ocr_res:
- if '企业注册号' in item['words']:
- # print('come in 111')
- reg_number = item['words'].split(':', 1)[1].strip()
- elif '企业名称' in item['words']:
- # print('come in 222')
- company_name = item['words'].split(':', 1)[1].strip()
- elif '所:' in item['words']:
- # print('come in 333')
- address = item['words'].split(':', 1)[1].strip()
- # 输出结果
- print("企业注册号:", reg_number)
- print("企业名称:", company_name)
- print("住所:", address)
- print("yanzhenghcenggong")
- # 截取图片保存 第三次截屏,保存到本地
- #将图片传给第三方verify接口得到需要移动的距离
- #result = slide_verify('cropped_verify_screenshot.png')
- #print(f'滑动距离:{result}')
- # self.drug_slide(340)
- # print('开始滑动')
- # self.d.swipe(120, 760, 460, 760, 0.3)
- # print('滑动结束')
- # time.sleep(1000000)
- #截图获取需要验证的内容
- def get_license_info(self):
- self.enter_shop()
- self.enter_shoper()
- self.scan_shoper_license()
- # 获取资质编码
- qualification_number = self.get_qualification_number()
- if qualification_number:
- table_license_info = self.get_table_license_info(qualification_number)
- if table_license_info:
- return {
- '单位名称': table_license_info[0],
- '地址': table_license_info[1],
- '社会信用代码': table_license_info[2]
- }
- else:
- # operate_no = random.randint(0, 1)
- self.d.click(0.603, 0.27)
- # if operate_no == 0:
- # self.d.xpath('//*[@text="营业执照"]').click()
- # else:
- # self.d.click(0.603, 0.27)
- time.sleep(self.get_sleep_time())
- self.screenshot_the_business_license()
- ocr_res = self.get_ocr_res('cropped_screenshot.png')
- return ocr_res
- # operate_no = random.randint(0, 1)
- self.d.click(0.603, 0.27)
- # if operate_no == 0:
- # self.d.xpath('//*[@text="营业执照"]').click()
- # else:
- # self.d.click(0.603, 0.27)
- time.sleep(self.get_sleep_time())
- self.screenshot_the_business_license()
- ocr_res = self.get_ocr_res('cropped_screenshot.png')
- return ocr_res
- def distinct_target(self):
- result = False
- is_position = self.d.xpath('//*[@content-desc="拍照搜索"]').exists
- is_position2 = self.d.xpath('//*[@text="年货节大促"]').exists
- is_position3 = self.d.xpath('//*[@text="筛选"]').exists
- is_position4 = self.d.xpath('//*[@text="回头客常拼"]').exists
- list_page_xpath = '//*[@resource-id="android:id/content"]/android.widget.FrameLayout[1]/android.widget.FrameLayout[1]/android.widget.FrameLayout[1]/android.widget.FrameLayout[1]/android.widget.FrameLayout[1]/android.widget.FrameLayout[2]/android.view.ViewGroup[1]/android.widget.LinearLayout[1]//android.support.v7.widget.RecyclerView[1]'
- is_position_new = self.d.xpath(list_page_xpath).exists
- print(f'is_position_new={is_position_new}')
- if is_position or is_position2 or is_position3 or is_position4 or is_position_new:
- result = True
- return result
- def enter_target_page(self):
- self.d.xpath('//*[@resource-id="android:id/content"]/android.widget.RelativeLayout[1]/android.widget.FrameLayout[1]/android.widget.FrameLayout[1]/android.widget.LinearLayout[1]/android.widget.FrameLayout[1]/android.widget.LinearLayout[1]').click()
- time.sleep(self.get_sleep_time())
- self.d(className='android.widget.EditText').click()
- time.sleep(self.get_sleep_time())
- self.d.send_keys(self.search_key, clear=True)
- time.sleep(self.get_sleep_time())
- self.d.xpath('//*[@text="搜索"]').click()
- time.sleep(self.get_sleep_time())
- """暂不用该功能
- def get_table_license_info(self, qualification_number):
- try:
- sql = f'select business_license_company,city,credit_code from mt_drug where credit_code = "{qualification_number}"'
- self.mysql_client.cur.execute(sql)
- res = self.mysql_client.cur.fetchone()
- return res
- except:
- return None
- """
- def get_clipboard(self):
- self.loggerPdd.info(f"Clipboard content:{self.d.clipboard}") # 打印调试信息
- clipboard_content = self.d.clipboard
- if clipboard_content is None:
- return ''
- return clipboard_content.strip()
- def clear_clipboard(self):
- self.d.set_clipboard("")
- def get_product_link(self):
- product_link = ''
- print('开始获取商品链接')
- content_frame = self.d.xpath('//*[@resource-id="android:id/content"]/android.widget.FrameLayout[1]').exists
- print(content_frame)
- relative_layout = self.d.xpath('//*[@resource-id="android:id/content"]/android.widget.FrameLayout[1]/android.widget.RelativeLayout[1]').exists
- print(relative_layout)
- relative_layout2 = self.d.xpath('//*[@resource-id="android:id/content"]/android.widget.FrameLayout[1]/android.widget.RelativeLayout[1]/android.widget.RelativeLayout[1]').exists
- print(relative_layout2)
- Frame_Layout = self.d.xpath('//*[@resource-id="android:id/content"]/android.widget.FrameLayout[1]/android.widget.RelativeLayout[1]/android.widget.RelativeLayout[1]/android.widget.FrameLayout[2]').exists
- print(Frame_Layout)
- ImageView = self.d.xpath('//*[@resource-id="android:id/content"]/android.widget.FrameLayout[1]/android.widget.RelativeLayout[1]/android.widget.RelativeLayout[1]/android.widget.FrameLayout[2]/android.view.View[1]').exists
- print(ImageView)
- ImageView2 = self.d.xpath('//*[@resource-id="android:id/content"]/android.widget.FrameLayout[1]/android.widget.RelativeLayout[1]/android.widget.RelativeLayout[1]/android.widget.FrameLayout[3]/android.view.View[1]').exists
- print(ImageView2)
- # time.sleep(10000)
- '''
- if self.d.xpath('//*[@resource-id="android:id/content"]/android.widget.FrameLayout[1]/android.widget.RelativeLayout[1]/android.widget.RelativeLayout[1]/android.widget.FrameLayout[2]/android.view.View[1]').exists:
- self.d.xpath('//*[@resource-id="android:id/content"]/android.widget.FrameLayout[1]/android.widget.RelativeLayout[1]/android.widget.RelativeLayout[1]/android.widget.FrameLayout[2]/android.view.View[1]').click()
- print('进入分享成功')
- time.sleep(1)
- #先清除剪切板的数据
- # self.clear_clipboard()
- #需要增加从右往左的滑动
- # self.d.swipe_ext("left", 0.5)
- print('开始滑动')
- self.d.swipe(400, 1250, 100, 1250, 0.2)
- time.sleep(0.2)
- if self.d.xpath('//*[@text="复制链接"]').exists:
- self.d.xpath('//*[@text="复制链接"]').click()
- print('点击复制链接')
- # self.d.xpath('//*[@text="复制链接"]').click_exists()
- # self.d.xpath('//*[contains(@text="复")]').click_exists()
- # time.sleep(1)
- product_link = self.get_clipboard()
- time.sleep(0.5)
- print(f'商品链接:{product_link}')
- elif self.d.xpath('//*[@resource-id="android:id/content"]/android.widget.FrameLayout[1]/android.widget.RelativeLayout[1]/android.widget.RelativeLayout[1]/android.widget.FrameLayout[3]/android.view.View[1]').exists:
- self.d.xpath('//*[@resource-id="android:id/content"]/android.widget.FrameLayout[1]/android.widget.RelativeLayout[1]/android.widget.RelativeLayout[1]/android.widget.FrameLayout[3]/android.view.View[1]').click()
- print('进入分享成功111')
- time.sleep(1)
- print('开始滑动')
- self.d.swipe(400, 1250, 100, 1250, 0.2)
- time.sleep(0.2)
- if self.d.xpath('//*[@text="复制链接"]').exists:
- self.d.xpath('//*[@text="复制链接"]').click()
- print('点击复制链接')
- product_link = self.get_clipboard()
- time.sleep(0.5)
- print(f'商品链接:{product_link}')
- else:
- print('进入分享失败')
- time.sleep(10000)
- '''
- # 多种可能的“分享”按钮
- dots_xpaths = [
- # '//*[@resource-id="android:id/content"]/android.widget.FrameLayout[1]/android.widget.RelativeLayout[1]/android.widget.RelativeLayout[1]/android.widget.FrameLayout[2]/android.view.View[1]',
- '//*[@resource-id="android:id/content"]/android.widget.FrameLayout[1]/android.widget.RelativeLayout[1]/android.widget.RelativeLayout[1]/android.widget.FrameLayout[last()]/android.view.View[1]',
- # '//*[@resource-id="android:id/content"]/android.widget.FrameLayout[1]/android.widget.RelativeLayout[2]/android.widget.RelativeLayout[1]/android.widget.FrameLayout[2]/android.view.View[1]',
- # '//*[@resource-id="android:id/content"]/android.widget.FrameLayout[1]/android.widget.RelativeLayout[2]/android.widget.RelativeLayout[2]/android.widget.FrameLayout[3]/android.widget.ImageView[1]',
- ]
- max_retry = 5 # 最多尝试次数
- for idx in range(1, max_retry + 1):
- if product_link: # 已经拿到则退出
- break
- for xp in dots_xpaths:
- if self.d.xpath(xp).exists:
- # print(f'{idx}-进入分享点点点')
- self.loggerPdd.info(f'{idx}-进入分享点点点')
- self.d.xpath(xp).click()
- time.sleep(1)
- # self.d.xpath('//*[@text="分享商品"]').click_exists()
- # time.sleep(0.2)
- # print('开始滑动')
- self.loggerPdd.info('开始滑动')
- if (self.device_id == '2e58510' or self.device_id == 'fcb3c749' or self.device_id == 'ea4e4eb8' or self.device_id == '95b2c764' or
- self.device_id == '369dcf96' or self.device_id == 'ZDQWUSSWBEDI896T' or self.device_id == 'IRLZAAQCDMHYWKTS' or
- self.device_id == 'U47HZDRG8XJBBURW' or self.device_id == 'WWRO9LTGG6KFGQCM' or self.device_id == 'fcb3c749' or
- self.device_id == 'OVFETO8PCY45E6A6' or self.device_id == 'U8ONIJJJS4CELVD6'):
- self.d.swipe(400, 1350, 100, 1350, 0.3)
- elif (self.device_id == 'KNNNEMNVWCJZQOLZ' or self.device_id == 'CMKFUSSG99ROR489' or self.device_id == '656DTOPRZDEALZ5X' or
- self.device_id == 'UCQGF6CQFMU8WKHI' or self.device_id == '4TZDUGTOAIFMJVGU' or self.device_id == 'DEZXWKUC7DJBLVPJ' or
- self.device_id == 'GQIRKB7LVOONM7VW'):
- self.d.swipe(400, 1300, 100, 1300, 0.3)
- elif self.device_id == 'e2899b34':
- self.d.swipe(400, 1050, 100, 1050, 0.3)
- else:
- self.d.swipe(400, 1250, 100, 1250, 0.3)
- # self.d.swipe(400, 1250, 100, 1250, 0.3)
- # self.d.drag(300, 1280, 50, 1280, 0.3)
- # self.d.swipe_ext('left', 0.3)
- time.sleep(0.2)
- self.d.xpath('//*[@text="复制链接"]').click_exists()
- time.sleep(1)
- product_link = self.get_clipboard()
- time.sleep(0.5)
- # print(f'{idx}-商品链接:{product_link}')
- self.loggerPdd.info(f'{idx}-商品链接:{product_link}')
- break # 找到并执行后跳出内层循环
- # if self.d.xpath('//*[@text="复制链接"]').exists:
- # self.d.xpath('//*[@text="复制链接"]').click()
- # # print('点击复制链接')
- # self.loggerPdd.info('点击复制链接')
- # product_link = self.get_clipboard()
- # time.sleep(0.5)
- # # print(f'{idx}-商品链接:{product_link}')
- # self.loggerPdd.info(f'{idx}-商品链接:{product_link}')
- # break # 找到并执行后跳出内层循环
- if not product_link and idx < max_retry:
- time.sleep(0.5) # 最后一次不需要再等待
- # time.sleep(100000)
- return product_link
- def _init_oss_bucket(self):
- # 仅做OSS配置校验和Bucket连接,无额外功能
- if not all([self.oss_config.get("access_key_id"),
- self.oss_config.get("access_key_secret"),
- self.oss_config.get("endpoint"),
- self.oss_config.get("bucket_name")]):
- print("OSS配置不完整,无法上传")
- return None
- try:
- auth = oss2.Auth(self.oss_config["access_key_id"], self.oss_config["access_key_secret"])
- bucket = oss2.Bucket(auth, self.oss_config["endpoint"], self.oss_config["bucket_name"])
- bucket.get_bucket_info() # 验证连接
- print("OSS Bucket连接成功")
- return bucket
- except Exception as e:
- print(f"OSS Bucket连接失败: {e}")
- return None
- #上传oss
- def _upload_to_oss(self, local_path):
- # 极简上传逻辑,仅返回OSS URL或None
- if not self.oss_bucket or not os.path.exists(local_path):
- return None
- file_name = os.path.basename(local_path)
- safe_name = re.sub(r'[^\w\.\-]', '_', file_name)
- oss_key = f"{self.oss_config.get('oss_prefix', 'scrape_data/')}{safe_name}"
- try:
- oss2.resumable_upload(self.oss_bucket, oss_key, local_path)
- # 生成并返回完整OSS URL
- oss_file_url = f"https://{self.oss_config['bucket_name']}.{self.oss_config['endpoint']}/{urllib.parse.quote(oss_key, safe='/')}"
- print(f"OSS上传成功: {oss_file_url}")
- return oss_file_url
- except Exception as e:
- print(f"OSS上传失败: {e}")
- return None
- def integrate_data(self):
- """
- 整合数据
- :return:
- """
- #测试通过点击店铺获取店铺的名称:
- # shop = self.get_shop_name()
- # print(f'店铺名称:{shop}')
- # time.sleep(100000)
- #测试点击店铺进入获取店铺资质
- # license_info = self.get_license_info_ex('1234')#店铺名称
- # time.sleep(100000)
- #首先判断是否存在:商品已售罄,推荐以下相似商品 的文本
- # if self.d.xpath('//*[contains(@text, "商品已售罄,推荐以下相似商品")]'):
- # self.loggerPdd.info(f'商品已售罄:{self.search_key}')
- # self.swipe_back(1)
- # return
- #获取价格和盒数备注
- min_price, ext = self.drug_price_ex() # 最低价格和盒数备注
- title_info = self.get_title() # 药品名字
- if title_info:
- if '999' in self.search_key:
- temp_search_key = self.search_key.replace('999', '')
- if self.search_key == '999强力枇杷露225ml':
- temp_search_key = temp_search_key.replace('225ml', '')
- elif self.search_key == '999糠酸莫米松凝胶15':
- temp_search_key = temp_search_key.replace('15', '')
- elif self.search_key == '999养胃舒颗粒10g*10':
- temp_search_key = temp_search_key.replace('10g*10', '')
- elif self.search_key == '999曲安奈德益康唑乳膏30g':
- temp_search_key = temp_search_key.replace ('30g', '')
- elif self.search_key == '999抗病毒口服液10ml*6支':
- temp_search_key = temp_search_key.replace('10ml*6支', '')
- elif self.search_key == '999复方板蓝根颗粒15袋':
- temp_search_key = temp_search_key.replace('15袋', '')
- elif self.search_key == '999可调式生理性海水鼻腔喷雾50':
- temp_search_key = temp_search_key.replace('50', '')
- elif self.search_key == '999维生素E.C颗粒9袋':
- temp_search_key = temp_search_key.replace('9袋', '')
- elif self.search_key == '999复方氨酚烷胺胶囊6粒':
- temp_search_key = temp_search_key.replace('6粒', '')
- elif self.search_key == '999复方板蓝根颗粒15g*15袋':
- temp_search_key = temp_search_key.replace('15g*15袋', '')
- elif self.search_key == '999止泻利颗粒15g*8':
- temp_search_key = temp_search_key.replace('15g*8', '')
- elif self.search_key == '999三蛇胆川贝膏138':
- temp_search_key = temp_search_key.replace('138', '')
- elif self.search_key == '999强力枇杷露16袋':
- temp_search_key = temp_search_key.replace('16袋', '')
- elif self.search_key == '999复方苦参肠炎康片12片':
- temp_search_key = temp_search_key.replace('12片', '')
- elif self.search_key == '999必无忧盐酸特比萘芬乳膏15':
- temp_search_key = temp_search_key.replace('必无忧', '')
- temp_search_key = temp_search_key.replace('15', '')
- elif self.search_key == '999速复康布洛芬缓释胶囊':
- temp_search_key = temp_search_key.replace('速复康', '')
- elif self.search_key == '999强力枇杷露120ml':
- temp_search_key = temp_search_key.replace('120ml', '')
- elif self.search_key == '999强力枇杷露150ml':
- temp_search_key = temp_search_key.replace('150ml', '')
- elif self.search_key == '999抗病毒口服液10ml*10':
- temp_search_key = temp_search_key.replace('10ml*10', '')
- elif self.search_key == '999抗病毒口服液10ml*12':
- temp_search_key = temp_search_key.replace('10ml*12', '')
- elif self.search_key == '999感冒清热颗粒6g*10':
- temp_search_key = temp_search_key.replace('6g*10', '')
- elif self.search_key == '999选平硝酸咪康唑乳膏20g':
- temp_search_key = temp_search_key.replace('选平', '')
- temp_search_key = temp_search_key.replace('20g', '')
- elif self.search_key == '999糠酸莫米松乳膏10g':
- temp_search_key = temp_search_key.replace('10g', '')
- elif self.search_key == '999壮骨关节丸6g*20':
- temp_search_key = temp_search_key.replace('6g*20', '')
- elif self.search_key == '999正天丸6g*15':
- temp_search_key = temp_search_key.replace('6g*15', '')
- elif self.search_key == '999藿香正气合剂10ml*6':
- temp_search_key = temp_search_key.replace('10ml*6', '')
- elif self.search_key == '999藿香正气合剂10ml*10':
- temp_search_key = temp_search_key.replace('10ml*10', '')
- elif self.search_key == '999小儿止咳糖浆120':
- temp_search_key = temp_search_key.replace('120', '')
- # elif self.search_key == '999小儿止咳糖浆100':
- # temp_search_key = temp_search_key.replace('100', '')
- elif self.search_key == '999小儿止咳糖浆225':
- temp_search_key = temp_search_key.replace('225', '')
- elif self.search_key == '999小儿感冒颗粒6g*10':
- temp_search_key = temp_search_key.replace('6g*10', '')
- elif self.search_key == '999小儿感冒颗粒6g*24':
- temp_search_key = temp_search_key.replace('6g*24', '')
- elif self.search_key == '999小儿氨酚黄那敏颗粒6g*10袋':
- temp_search_key = temp_search_key.replace('6g*10袋', '')
- elif self.search_key == '999小儿氨酚黄那敏颗粒6g*20袋':
- temp_search_key = temp_search_key.replace('6g*20袋', '')
- elif self.search_key == '999感冒灵颗粒10g*9袋':
- temp_search_key = temp_search_key.replace('10g*9袋', '')
- elif self.search_key == '999皮炎平复方醋酸地塞米松乳膏20':
- temp_search_key = temp_search_key.replace('皮炎平', '')
- temp_search_key = temp_search_key.replace('20', '')
- elif self.search_key == '999糠酸莫米松凝胶10':
- temp_search_key = temp_search_key.replace('10', '')
- elif self.search_key == '999板蓝根颗粒10g*20':
- temp_search_key = temp_search_key.replace('10g*20', '')
- elif self.search_key == '999咽炎片0.26g*12片':
- temp_search_key = temp_search_key.replace('0.26g*12片', '')
- elif self.search_key == '999小儿咽扁颗粒8g*10袋':
- temp_search_key = temp_search_key.replace('8g*10袋', '')
- elif self.search_key == '999感冒清热颗粒12g*18':
- temp_search_key = temp_search_key.replace('12g*18', '')
- elif self.search_key == '999小柴胡颗粒10g*15':
- temp_search_key = temp_search_key.replace('10g*15', '')
- # print (f"temp_search_key={temp_search_key}")
- if self.search_key == '999抗病毒口服液': #如果标题不包含 999 或 抗病毒口服液 或 (10ml*12 和 10ml*18) 则退出
- if '999' not in title_info or temp_search_key not in title_info:
- print(f"当前商品名称:{title_info} 不包含关键字:{self.search_key}")
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- elif '10ml*12' not in title_info and '10ml*10' not in title_info:
- print(f"当前商品名称:{title_info} 不包含10*12或10*10品规")
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- elif self.search_key == '999抗病毒口服液10ml*6支': #如果标题不包含 999 或 抗病毒口服液 或 (10ml*12 和 10ml*18) 则退出
- if '999' not in title_info or temp_search_key not in title_info:
- print(f"当前商品名称:{title_info} 不包含关键字:{self.search_key}")
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- elif '10ml*6' not in title_info:
- print(f"当前商品名称:{title_info} 不包含10ml*6品规")
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- elif self.search_key == '999曲安奈德益康唑乳膏30g':
- if '999' not in title_info or temp_search_key not in title_info:
- print(f"当前商品名称:{title_info} 不包含关键字:{self.search_key}")
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- elif '30' not in title_info:
- print(f"当前商品名称:{title_info} 不包含30品规")
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- elif self.search_key == '999复方感冒灵颗粒':
- if '999' not in title_info or temp_search_key not in title_info :
- print(f"当前商品名称:{title_info} 不包含关键字:{self.search_key}")
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- elif '14g*15' not in title_info:
- print(f"当前商品名称:{title_info} 不包含14g*15品规")
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- elif self.search_key == '999养胃舒颗粒10g*10':
- if '999' not in title_info or temp_search_key not in title_info :
- print(f"当前商品名称:{title_info} 不包含关键字:{self.search_key}")
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- elif '10g*10' not in title_info:
- print(f"当前商品名称:{title_info} 不包含10g*10品规")
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- elif self.search_key == '999糠酸莫米松凝胶15':
- if '999' not in title_info or temp_search_key not in title_info :
- print(f"当前商品名称:{title_info} 不包含关键字:{self.search_key}")
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- elif '15' not in title_info:
- print(f"当前商品名称:{title_info} 不包含15品规")
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- elif self.search_key == '999强力枇杷露225ml':
- if '999' not in title_info or temp_search_key not in title_info :
- print(f"当前商品名称:{title_info} 不包含关键字:{self.search_key}")
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- elif '225' not in title_info:
- print(f"当前商品名称:{title_info} 不包含225品规")
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- elif self.search_key == '999强力枇杷露120ml':
- if '999' not in title_info or temp_search_key not in title_info :
- print(f"当前商品名称:{title_info} 不包含关键字:{self.search_key}")
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- elif '120' not in title_info:
- print(f"当前商品名称:{title_info} 不包含120品规")
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- elif self.search_key == '999强力枇杷露150ml':
- if '999' not in title_info or temp_search_key not in title_info :
- print(f"当前商品名称:{title_info} 不包含关键字:{self.search_key}")
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- elif '150' not in title_info:
- print(f"当前商品名称:{title_info} 不包含150品规")
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- elif self.search_key == '999抗病毒口服液10ml*10':
- if '999' not in title_info or temp_search_key not in title_info :
- print(f"当前商品名称:{title_info} 不包含关键字:{self.search_key}")
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- elif '10ml*10' not in title_info:
- print(f"当前商品名称:{title_info} 不包含10ml*10品规")
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- elif self.search_key == '999抗病毒口服液10ml*12':
- if '999' not in title_info or temp_search_key not in title_info :
- print(f"当前商品名称:{title_info} 不包含关键字:{self.search_key}")
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- elif '10ml*12' not in title_info:
- print(f"当前商品名称:{title_info} 不包含10ml*12品规")
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- elif self.search_key == '999复方板蓝根颗粒15袋':
- if '999' not in title_info or temp_search_key not in title_info :
- print(f"当前商品名称:{title_info} 不包含关键字:{temp_search_key}")
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- elif '15袋' not in title_info:
- print(f"当前商品名称:{title_info} 不包含15袋品规")
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- elif self.search_key == '999可调式生理性海水鼻腔喷雾50':
- if '999' not in title_info or temp_search_key not in title_info :
- print(f"当前商品名称:{title_info} 不包含关键字:{temp_search_key}")
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- elif self.search_key == '999维生素E.C颗粒9袋':
- if '999' not in title_info or temp_search_key not in title_info :
- print(f"当前商品名称:{title_info} 不包含关键字:{temp_search_key}")
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- elif self.search_key == '999复方氨酚烷胺胶囊6粒':
- if '999' not in title_info or temp_search_key not in title_info :
- print(f"当前商品名称:{title_info} 不包含关键字:{temp_search_key}")
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- elif '6粒' not in title_info:
- print(f"当前商品名称:{title_info} 不包含6粒品规")
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- elif self.search_key == '999复方板蓝根颗粒15g*15袋':
- if '999' not in title_info or temp_search_key not in title_info :
- print(f"当前商品名称:{title_info} 不包含关键字:{temp_search_key}")
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- elif '15g*15' not in title_info:
- print(f"当前商品名称:{title_info} 不包含15g*15品规")
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- elif self.search_key == '999止泻利颗粒15g*8':
- if '999' not in title_info or temp_search_key not in title_info :
- print(f"当前商品名称:{title_info} 不包含关键字:{temp_search_key}")
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- elif '15g*8' not in title_info:
- print(f"当前商品名称:{title_info} 不包含15g*8品规")
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- elif self.search_key == '999三蛇胆川贝膏138':
- if '999' not in title_info or temp_search_key not in title_info :
- print(f"当前商品名称:{title_info} 不包含关键字:{temp_search_key}")
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- elif '138' not in title_info:
- print(f"当前商品名称:{title_info} 不包含138品规")
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- elif self.search_key == '999强力枇杷露16袋':
- if '999' not in title_info or temp_search_key not in title_info :
- print(f"当前商品名称:{title_info} 不包含关键字:{temp_search_key}")
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- elif '16袋' not in title_info:
- print(f"当前商品名称:{title_info} 不包含16袋品规")
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- elif self.search_key == '999复方苦参肠炎康片12片':
- if '999' not in title_info or temp_search_key not in title_info :
- print(f"当前商品名称:{title_info} 不包含关键字:{temp_search_key}")
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- elif '12片' not in title_info:
- print(f"当前商品名称:{title_info} 不包含12片品规")
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- elif self.search_key == '999必无忧盐酸特比萘芬乳膏15':
- if temp_search_key not in title_info :
- print(f"当前商品名称:{title_info} 不包含关键字:{temp_search_key}")
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- elif ('999' not in title_info) and ('必无忧' not in title_info):
- print(f"当前商品名称:{title_info} 不包含关键字:999或 必无忧")
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- elif '15' not in title_info:
- print(f"当前商品名称:{title_info} 不包含15品规")
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- elif self.search_key == '999速复康布洛芬缓释胶囊':
- if temp_search_key not in title_info :
- print(f"当前商品名称:{title_info} 不包含关键字:{temp_search_key}")
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- elif ('999' not in title_info) and ('速复康' not in title_info):
- print(f"当前商品名称:{title_info} 不包含关键字:999或 速复康")
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- elif self.search_key == '999维生素C咀嚼片':
- if '999' not in title_info or temp_search_key not in title_info :
- print(f"当前商品名称:{title_info} 不包含关键字:{temp_search_key}")
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- elif '80' not in title_info:
- print(f"当前商品名称:{title_info} 不包含80品规")
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- elif self.search_key == '999精氨酸布洛芬颗粒':
- if '999' not in title_info or temp_search_key not in title_info :
- print(f"当前商品名称:{title_info} 不包含关键字:{temp_search_key}")
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- elif '9' not in title_info:
- print(f"当前商品名称:{title_info} 不包含9品规")
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- elif self.search_key == '999阿奇霉素片':
- if '999' not in title_info or temp_search_key not in title_info :
- print(f"当前商品名称:{title_info} 不包含关键字:{temp_search_key}")
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- elif '0.25g*6' not in title_info:
- print(f"当前商品名称:{title_info} 不包含0.25g*6品规")
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- elif self.search_key == '999感冒清热颗粒6g*10':
- if '999' not in title_info or temp_search_key not in title_info :
- print(f"当前商品名称:{title_info} 不包含关键字:{temp_search_key}")
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- elif '6g*10' not in title_info:
- print(f"当前商品名称:{title_info} 不包含6g*10品规")
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- elif self.search_key == '999选平硝酸咪康唑乳膏20g':
- if temp_search_key not in title_info :
- print(f"当前商品名称:{title_info} 不包含关键字:{temp_search_key}")
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- elif ('999' not in title_info) and ('选平' not in title_info):
- print(f"当前商品名称:{title_info} 不包含关键字:999或 选平")
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- elif '20g' not in title_info:
- print(f"当前商品名称:{title_info} 不包含20g品规")
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- elif self.search_key == '999糠酸莫米松乳膏10g':
- if '999' not in title_info or temp_search_key not in title_info :
- print(f"当前商品名称:{title_info} 不包含关键字:{temp_search_key}")
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- elif '10g' not in title_info:
- print(f"当前商品名称:{title_info} 不包含10g品规")
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- elif self.search_key == '999补脾益肠丸':
- if temp_search_key not in title_info :
- print(f"当前商品名称:{title_info} 不包含关键字:{temp_search_key}")
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- elif ('999' not in title_info) and ('三九' not in title_info):
- print(f"当前商品名称:{title_info} 不包含关键字:999或 三九")
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- elif self.search_key == '999壮骨关节丸6g*20':
- if '999' not in title_info or temp_search_key not in title_info :
- print(f"当前商品名称:{title_info} 不包含关键字:{temp_search_key}")
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- elif '6g*20' not in title_info:
- print(f"当前商品名称:{title_info} 不包含6g*20品规")
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- elif self.search_key == '999正天丸6g*15':
- if '999' not in title_info or temp_search_key not in title_info :
- print(f"当前商品名称:{title_info} 不包含关键字:{temp_search_key}")
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- elif '6g*15' not in title_info:
- print(f"当前商品名称:{title_info} 不包含6g*15品规")
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- elif self.search_key == '999藿香正气合剂10ml*6':
- if '999' not in title_info or temp_search_key not in title_info :
- print(f"当前商品名称:{title_info} 不包含关键字:{temp_search_key}")
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- elif '10ml*6' not in title_info:
- print(f"当前商品名称:{title_info} 不包含10ml*6品规")
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- elif self.search_key == '999藿香正气合剂10ml*10':
- if '999' not in title_info or temp_search_key not in title_info :
- print(f"当前商品名称:{title_info} 不包含关键字:{temp_search_key}")
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- elif '10ml*10' not in title_info:
- print(f"当前商品名称:{title_info} 不包含10ml*10品规")
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- elif self.search_key == '999小儿止咳糖浆120':
- if '999' not in title_info or temp_search_key not in title_info :
- print(f"当前商品名称:{title_info} 不包含关键字:{temp_search_key}")
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- elif '120' not in title_info:
- print(f"当前商品名称:{title_info} 不包含120品规")
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- elif self.search_key == '999小儿止咳糖浆100':
- if '999' not in title_info or temp_search_key not in title_info :
- print(f"当前商品名称:{title_info} 不包含关键字:{temp_search_key}")
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- elif '100' not in title_info:
- print(f"当前商品名称:{title_info} 不包含100品规")
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- elif self.search_key == '999小儿止咳糖浆225':
- if '999' not in title_info or temp_search_key not in title_info :
- print(f"当前商品名称:{title_info} 不包含关键字:{temp_search_key}")
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- elif '225' not in title_info:
- print(f"当前商品名称:{title_info} 不包含225品规")
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- elif self.search_key == '999小儿感冒颗粒6g*10':
- if '999' not in title_info or temp_search_key not in title_info :
- print(f"当前商品名称:{title_info} 不包含关键字:{temp_search_key}")
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- elif '6g*10' not in title_info:
- print(f"当前商品名称:{title_info} 不包含6g*10品规")
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- elif self.search_key == '999小儿感冒颗粒6g*24':
- if '999' not in title_info or temp_search_key not in title_info :
- print(f"当前商品名称:{title_info} 不包含关键字:{temp_search_key}")
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- elif '6g*24' not in title_info:
- print(f"当前商品名称:{title_info} 不包含6g*24品规")
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- elif self.search_key == '999小儿氨酚黄那敏颗粒6g*10袋':
- if '999' not in title_info or temp_search_key not in title_info :
- print(f"当前商品名称:{title_info} 不包含关键字:{temp_search_key}")
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- elif '6g*10' not in title_info:
- print(f"当前商品名称:{title_info} 不包含6g*10品规")
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- elif self.search_key == '999小儿氨酚黄那敏颗粒6g*20袋':
- if '999' not in title_info or temp_search_key not in title_info :
- print(f"当前商品名称:{title_info} 不包含关键字:{temp_search_key}")
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- elif '6g*20' not in title_info:
- print(f"当前商品名称:{title_info} 不包含6g*20品规")
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- elif self.search_key == '999感冒灵颗粒':
- if '999' not in title_info or temp_search_key not in title_info :
- print(f"当前商品名称:{title_info} 不包含关键字:{temp_search_key}")
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- elif '10g*9' not in title_info:
- print(f"当前商品名称:{title_info} 不包含10g*9品规")
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- elif self.search_key == '999皮炎平复方醋酸地塞米松乳膏20':
- if temp_search_key not in title_info :
- print(f"当前商品名称:{title_info} 不包含关键字:{temp_search_key}")
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- elif ('999' not in title_info) and ('皮炎平' not in title_info):
- print(f"当前商品名称:{title_info} 不包含关键字:999或 皮炎平")
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- elif '20g' not in title_info:
- print(f"当前商品名称:{title_info} 不包含20g品规")
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- elif self.search_key == '999糠酸莫米松凝胶10':
- if '999' not in title_info or temp_search_key not in title_info :
- print(f"当前商品名称:{title_info} 不包含关键字:{self.search_key}")
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- elif '10' not in title_info:
- print(f"当前商品名称:{title_info} 不包含10品规")
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- elif self.search_key == '999板蓝根颗粒10g*20':
- if '999' not in title_info or temp_search_key not in title_info :
- print(f"当前商品名称:{title_info} 不包含关键字:{self.search_key}")
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- elif '10g*20' not in title_info:
- print(f"当前商品名称:{title_info} 不包含10g*20品规")
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- elif self.search_key == '999咽炎片0.26g*12片':
- if '999' not in title_info or temp_search_key not in title_info :
- print(f"当前商品名称:{title_info} 不包含关键字:{self.search_key}")
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- elif '0.26g*12' not in title_info and '0.26g*24' not in title_info:
- print(f"当前商品名称:{title_info} 不包含0.26g*12 和 0.26g*24品规")
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- elif self.search_key == '999感冒清热颗粒12g*18':
- if '999' not in title_info or temp_search_key not in title_info :
- print(f"当前商品名称:{title_info} 不包含关键字:{self.search_key}")
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- elif '12g*18' not in title_info:
- print(f"当前商品名称:{title_info} 不包含12g*18品规")
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- elif self.search_key == '999小儿咽扁颗粒8g*10袋':
- if '999' not in title_info or temp_search_key not in title_info :
- print(f"当前商品名称:{title_info} 不包含关键字:{self.search_key}")
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- elif '8g*10' not in title_info:
- print(f"当前商品名称:{title_info} 不包含8g*10品规")
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- elif self.search_key == '999小柴胡颗粒10g*15':
- if '999' not in title_info or temp_search_key not in title_info :
- print(f"当前商品名称:{title_info} 不包含关键字:{self.search_key}")
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- elif '15' not in title_info:
- print(f"当前商品名称:{title_info} 不包含15品规")
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- else:
- if '999' not in title_info or temp_search_key not in title_info:
- print(f"当前商品名称:{title_info} 不包含关键字:{self.search_key}")
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- else:
- if self.search_key == '史达功右美沙芬愈创甘油醚糖浆120':
- temp_search_key = self.search_key.replace('史达功', '')
- temp_search_key = temp_search_key.replace('120', '')
- if '史达功' not in title_info or temp_search_key not in title_info:
- print(f'药品标题未包含药品关键字:-->{temp_search_key}')
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- elif '120' not in title_info:
- print(f"当前商品名称:{title_info} 不包含120品规")
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- elif self.search_key == '三九胃泰养胃舒颗粒8袋':
- temp_search_key = self.search_key.replace('三九胃泰', '')
- temp_search_key = temp_search_key.replace('8袋', '')
- if '三九胃泰' not in title_info or temp_search_key not in title_info:
- print(f'药品标题未包含药品关键字:-->{temp_search_key}')
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- elif '8袋' not in title_info:
- print(f"当前商品名称:{title_info} 不包含8袋品规")
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- elif self.search_key == '三九复方金银花颗粒10g*8袋':
- temp_search_key = self.search_key.replace('三九', '')
- temp_search_key = temp_search_key.replace('10g*8袋', '')
- if '三九' not in title_info or temp_search_key not in title_info:
- print(f'药品标题未包含药品关键字:-->{temp_search_key}')
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- elif '10g*8' not in title_info:
- print(f"当前商品名称:{title_info} 不包含10g*8品规")
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- elif self.search_key == '必无忧盐酸特比萘芬喷雾剂30ml':
- temp_search_key = self.search_key.replace('必无忧', '')
- temp_search_key = temp_search_key.replace('30ml', '')
- if '必无忧' not in title_info or temp_search_key not in title_info:
- print(f'药品标题未包含药品关键字:-->{temp_search_key}')
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- elif '30' not in title_info:
- print(f"当前商品名称:{title_info} 不包含30品规")
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- elif self.search_key == '佳美舒阿奇霉素肠溶胶囊4':
- temp_search_key = self.search_key.replace('佳美舒', '')
- temp_search_key = temp_search_key.replace('4', '')
- if '佳美舒' not in title_info or temp_search_key not in title_info:
- print(f'药品标题未包含药品关键字:-->{temp_search_key}')
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- elif '4' not in title_info and '8' not in title_info:
- print(f"当前商品名称:{title_info} 不包含4品规或8品规")
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- elif self.search_key == '三九胃泰颗粒20g*10':
- temp_search_key = self.search_key.replace('20g*10', '')
- if temp_search_key not in title_info:
- print(f'药品标题未包含药品关键字:-->{temp_search_key}')
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- elif '20g*10' not in title_info:
- print(f"当前商品名称:{title_info} 不包含20g*10品规")
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- elif self.search_key == '三九胃泰颗粒2.5g*6':
- temp_search_key = self.search_key.replace('2.5g*6', '')
- if temp_search_key not in title_info:
- print(f'药品标题未包含药品关键字:-->{temp_search_key}')
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- elif '2.5g*6' not in title_info:
- print(f"当前商品名称:{title_info} 不包含2.5g*6品规")
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- elif self.search_key == '三九胃泰颗粒20g*6袋':
- temp_search_key = self.search_key.replace('20g*6袋', '')
- if temp_search_key not in title_info:
- print(f'药品标题未包含药品关键字:-->{temp_search_key}')
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- elif '20g*6' not in title_info:
- print(f"当前商品名称:{title_info} 不包含20g*6品规")
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- elif self.search_key == '顺峰酮康他索乳膏':
- temp_search_key = self.search_key.replace('顺峰', '')
- if temp_search_key not in title_info or '顺峰' not in title_info:
- print(f'药品标题未包含药品关键字:-->{temp_search_key}')
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- elif self.search_key == '速复康磷酸奥司他韦胶囊75mg*10':
- temp_search_key = self.search_key.replace('速复康', '')
- temp_search_key = temp_search_key.replace('75mg*10', '')
- if '佳美舒' not in title_info or temp_search_key not in title_info:
- print(f'药品标题未包含药品关键字:-->{temp_search_key}')
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- elif '75mg*10' not in title_info:
- print(f"当前商品名称:{title_info} 不包含75mg*10品规")
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- else:
- if self.search_key not in title_info:
- print(f'药品标题未包含药品关键字:-->{self.search_key}')
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- # temp_search_key = self.search_key
- # if self.search_key == '三九胃泰颗粒':
- # temp_search_key = '三九胃泰' #兼容三九胃泰 温胃舒颗粒
- # elif '999' in self.search_key:
- # temp_search_key = self.search_key.replace('999', '')
- # if '999' in self.search_key:
- # if ('999' not in title_info) or (temp_search_key not in title_info):
- # print(f'药品标题未包含药品关键字:-->{temp_search_key}和未包含999')
- # self.swipe_back(1)
- # self.unrelated_data += 1
- # return
- # else:
- # if temp_search_key not in title_info:
- # print(f'药品标题未包含药品关键字:-->{temp_search_key}')
- # self.swipe_back(1)
- # self.unrelated_data += 1
- # return
- else:
- print('标题获取为空')
- self.swipe_back(1)
- return
- #第一次没有获取到价格
- if not min_price:
- min_price = self.drug_price() # 最低价格 第二次获取
- if not min_price:
- print('提取价格出错,回退到列表页')
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- # 商品链接 分享链接
- product_link = self.get_product_link()
- time.sleep(2)
- if self.search_key == '999小儿止咳糖浆' or self.search_key == '999小儿氨酚黄那敏颗粒' or self.search_key == '999小儿感冒颗粒':
- shop = self.get_shop_name()
- else:
- for i in range(15):
- if self.d(textStartsWith="进店").exists:
- print('开始获取店铺名')
- break
- screen_width = self.d.info['displayWidth']
- screen_height = self.d.info['displayHeight']
- # self.d.swipe(screen_width // 2, screen_height - 400, screen_width // 2, 400, duration=0.2)
- self.d.swipe_ext("up", scale=0.3)
- time.sleep(self.get_sleep_time())
- if self.d(textStartsWith="进店").exists:
- print('可以开始获取店铺名')
- # shop = self.get_shop_name()
- shop = self.get_shop_name()
- if not shop:
- print('当前店铺名称为空,返回商品列表页面')
- self.swipe_back(1)
- self.unrelated_data += 1
- return
- # 爬取日期
- scrape_date = self.get_current_date()
- if self.search_key == '999小柴胡颗粒10g*15':
- dup_search_key = '999小柴胡颗粒'
- else:
- dup_search_key = self.search_key
- dup_data = {'search_key': dup_search_key, 'min_price': min_price, 'shop': shop, 'scrape_date': scrape_date,
- 'platform': '拼多多'}
- if self.data_is_exists(dup_data):
- print('存在相同数据不入库')
- self.swipe_back(1)
- return
- is_has_instructions = self.has_instructions()
- # print(f'是否有说明书:{is_has_instructions}')
- self.loggerPdd.info(f'是否有说明书:{is_has_instructions}')
- # 生产日期为空
- manufacture_date = ''
- # 执政信息
- # if is_has_enter_shop:
- # license_info = self.get_license_info()
- # business_license_company = license_info["单位名称"]
- # credit_code = license_info['社会信用代码']
- # city_str = license_info['地址']
- # # 先把省份啥的替换掉
- # city_sub_str = re.sub(r'[u4e00-\u9fa5]+省', '', city_str)
- # try:
- # city = re.search(r'[\u4e00-\u9fa5]+?(市|区|县)', city_sub_str).group(0)
- # except:
- # city = city_sub_str
- # try:
- # province = self.city2province[city]
- # except:
- # province = ''
- # self.swipe_back(2)
- # else:
- # business_license_company = ''
- # credit_code = ''
- # city = ''
- # province = ''
- business_license_company = ''
- # credit_code = ''
- credit_code = ext
- city = ''
- province = ''
- # 说明书等信息
- if is_has_instructions:
- try:
- instructions_info = self.get_instructions_data()
- # print('说明书相关信息:', instructions_info)
- expiry_date = instructions_info['有效期'].strip('。')
- manufacturer = instructions_info['生产单位'].strip('。')
- approval_number = instructions_info['批准文号'].strip('。')
- specifications = instructions_info['产品规格'].strip('。')
- except Exception as e:
- print(f'获取详情页规格参数出错:{e}')
- self.swipe_back(2)
- return
- else:
- expiry_date = ''
- manufacturer = ''
- approval_number = ''
- specifications = ''
- # if self.search_key == '999小柴胡颗粒':
- # if '10g*9' in specifications or '10克x9' in specifications or '10g*15' in specifications or '10克/袋*9' in specifications:
- # print("111")
- # else:
- # self.swipe_back(1)
- # return
- # elif self.search_key == '':
- # if '10ml*12' in specifications or '10ml*18' in specifications:
- # print(222)
- # else:
- # self.swipe_back(1)
- # return
- self.unrelated_data = 0
- # 商品链接
- # product_link = ''
- # 爬取省份
- scrape_province = '广东' # 这里先默认广东
- # 是否有货
- availability = ''
- if self.search_key == '999小柴胡颗粒10g*15':
- save_search_key = '999小柴胡颗粒'
- else:
- save_search_key = self.search_key
- save_data = {
- 'product': title_info,
- 'min_price': min_price,
- 'manufacture_date': manufacture_date,
- 'expiry_date': expiry_date,
- 'shop': shop,
- 'business_license_company': business_license_company,
- 'province': province,
- 'city': city,
- 'manufacturer': manufacturer,
- 'specification': specifications,
- 'approval_number': approval_number,
- 'product_link': product_link,
- 'scrape_date': scrape_date,
- 'scrape_province': scrape_province,
- 'availability': availability,
- 'credit_code': credit_code,
- 'platform': '拼多多',
- 'search_key': save_search_key,
- 'number' : 1
- }
- # print(f'待插入数据:{save_data}')
- self.save_to_database(save_data)
- self.swipe_back(1)
- #获取店铺信息start 2025-07-28
- '''
- #不获取店铺信息
- #1、判断店铺名称是否已存在
- shop_is_exists = self.shop_is_exists_database(shop)
- #2、获取店铺资质 是否存在
- # is_has_shop_qualifications = self.has_shop_qualifications()
- if not shop_is_exists :
- print('开始获取店铺信息')
- #点击店铺,点击店铺标题,点击店铺资质
- # license_info = self.get_license_info_ex()
- else:
- #日志中加上店铺名称
- self.loggerPdd.info(f'店铺{shop}信息已存在数据库')
- #获取店铺信息end
- '''
- if self.distinct_target():
- print('已到达搜索列表页')
- else:
- for i in range(2):
- self.swipe_back(1)
- # 最外部有个定位按钮
- if self.distinct_target():
- break
- def main(self, device_id, search_key_length, keyword_idx):
- spider_no = 0
- self.connect_devices(device_id)
- time.sleep(self.get_sleep_time())
- print("搜索前,先重启APP")
- # 重新开启拼多多应用
- self.restart_app()
- # 搜索关键字
- self.enter_target_page()
- # if keyword_idx == 0:
- # print("搜索前,先重启APP")
- # # 重新开启拼多多应用
- # self.restart_app()
- # # 搜索关键字
- # self.enter_target_page()
- # else:
- # print("清空前面的文字,再输入关键词")
- # self.d.send_keys(self.search_key, clear=True)
- # time.sleep(self.get_sleep_time())
- # print("点击搜索")
- # self.d.xpath('//*[@text="搜索"]').click()
- # time.sleep(self.get_sleep_time())
- # # 3. 容错处理:点击失败时的兜底逻辑
- # self.swipe_up()
- for idx in range(300):
- print(f'第{idx + 1}页')
- if spider_no > 30:
- time.sleep(300)
- spider_no = 0
- if self.unrelated_data > 10:
- print(f'[{self.program_start_time}]----{self.search_key}----连续超过10个不达标的数据则停止采集')
- print(
- f"[程序启动时间:{self.program_start_time}-----程序结束时间:{self.app_current_time()}]----搜索关键词:{self.search_key}----点击了{self.click_counts}个商品")
- # self.swipe_down()
- # time.sleep(self.get_sleep_time()) # 下滑后等待页面稳定
- #
- # click_success = self.click_target_product_by_search_key(fuzzy_match=False)
- # if not click_success:
- # print(f"⚠️ 关键词「{self.search_key}」商品点击失败")
- # return
- #
- # print("点击搜索框")
- # self.d(className='android.widget.EditText').click()
- # time.sleep(self.get_sleep_time())
- if keyword_idx == search_key_length - 1:
- print("程序最后一个品规采集完毕,返回主屏幕")
- self.d.press("home")
- # 连续超过10个不达标的数据则停止采集
- break
- if self.max_counts >= 300 and self.search_key == '999糠酸莫米松凝胶10':
- print('enough')
- break
- if self.search_key == '顺峰酮康他索乳膏' and self.max_counts >= 300:
- print('enough')
- break
- # 售罄次数大于4基本就是号废了但是如果下次点击不会出现这种情况就要重置为0
- if self.sold_out_counts > 4:
- print(
- f"[程序启动时间:{self.program_start_time}-----程序结束时间:{self.app_current_time()}]----搜索关键词:{self.search_key}----点击了{self.click_counts}个商品")
- print("====商品已售罄4次,结束采集(号不能用),返回主屏幕====")
- self.d.press('home')
- break
- if idx == 0:
- drug_lis = self.d.xpath(
- '//*[@resource-id="android:id/content"]/android.widget.FrameLayout[1]/android.widget.FrameLayout[2]/android.widget.FrameLayout[1]/android.widget.FrameLayout[1]/android.widget.FrameLayout[1]/android.widget.FrameLayout[1]/android.support.v7.widget.RecyclerView[1]/android.widget.FrameLayout').all()
- else:
- for i in range(1, 6):
- drug_xpath = f'/hierarchy/android.widget.FrameLayout[{i}]/android.widget.LinearLayout[1]/android.widget.FrameLayout[1]/android.widget.FrameLayout[1]/android.widget.FrameLayout[1]/android.widget.FrameLayout[1]/android.widget.FrameLayout[1]/android.widget.FrameLayout[1]/android.widget.FrameLayout[1]/android.support.v7.widget.RecyclerView[1]/android.widget.FrameLayout'
- drug_lis = self.d.xpath(
- f'/hierarchy/android.widget.FrameLayout[{i}]/android.widget.LinearLayout[1]/android.widget.FrameLayout[1]/android.widget.FrameLayout[1]/android.widget.FrameLayout[1]/android.widget.FrameLayout[1]/android.widget.FrameLayout[1]/android.widget.FrameLayout[1]/android.widget.FrameLayout[1]/android.support.v7.widget.RecyclerView[1]/android.widget.FrameLayout').all()
- if drug_lis:
- break
- print('数量', len(drug_lis))
- for idd, drug_one in enumerate(drug_lis):
- print(idd+1, drug_one.info)
- time.sleep(self.get_sleep_time())
- # left = drug_one.info['bounds']['left']
- top = drug_one.info['bounds']['top']
- # right = drug_one.info['bounds']['right']
- bottom = drug_one.info['bounds']['bottom']
- # height = bottom - top
- # 高度低于多少的不点击采集
- # if bottom <= 1400 and top >= 258:
- if bottom <= 1524 and top >= 258:
- # print(f"这页的第{idd+1}个商品")
- # #商品名称的xpath
- # if idx == 0:
- # product_tittle_xpath = f'//*[@resource-id="android:id/content"]/android.widget.FrameLayout[1]/android.widget.FrameLayout[2]/android.widget.FrameLayout[1]/android.widget.FrameLayout[1]/android.widget.FrameLayout[1]/android.widget.FrameLayout[1]/android.support.v7.widget.RecyclerView[1]/android.widget.FrameLayout[{idd+2}]/android.widget.LinearLayout[1]/android.widget.FrameLayout[2]/android.widget.TextView'
- # else:
- # product_tittle_xpath = drug_xpath + f'[{idd+1}]/android.widget.LinearLayout[1]/android.widget.FrameLayout[2]/android.widget.TextView'
- # print(f"商品名称的xpath:{product_tittle_xpath}")
- # if self.d.xpath(product_tittle_xpath).exists:
- # # product_title = self.d.xpath(product_tittle_xpath).info['contentDescription']
- # print(f"列表当前info:{self.d.xpath(product_tittle_xpath).info}")
- # product_title = self.d.xpath(product_tittle_xpath).text
- # print(f"列表当前商品名称:{product_title}")
- # if '999' in self.search_key:
- # temp_search_key = self.search_key.replace('999', '')
- # if '999' not in product_title or temp_search_key not in product_title:
- # print(f"当前商品名称:{product_title} 不包含关键字:{self.search_key}")
- # continue
- # else:
- # if self.search_key not in product_title.replace(' ', ''):
- # continue
- # else:
- # print(f"列表当前商品路径不存在")
- drug_one.click()
- self.click_counts += 1
- time.sleep(self.get_sleep_time())
- # 先判断是否售罄次数是否大于4
- if self.sold_out_counts >= 4:
- print(f"[程序启动时间:{self.program_start_time}-----程序结束时间:{self.app_current_time()}]----搜索关键词:{self.search_key}----点击了{self.click_counts}个商品")
- print("====这是在第一页有两个,商品已售罄4次,结束采集(号不能用)====")
- time.sleep(self.get_sleep_time())
- self.d.press('home')
- return
- # 已售罄 self.sold_out_counts += 1
- if self.d.xpath('//*[contains(@text, "商品已售罄")]').wait(timeout=5):
- print("======商品已售罄======")
- self.sold_out_counts += 1
- self.swipe_back(1)
- continue
- # 采集药品信息
- try:
- # 重置商品售罄次数
- self.sold_out_counts = 0
- self.integrate_data()
- # 检测下是否回退到列表页
- if self.distinct_target():
- print('回退到列表页', True)
- else:
- print(f'[{self.app_current_time()}] 回退到列表页失败,终止采集')
- print(f"[程序启动时间:{self.program_start_time}-----程序结束时间:{self.app_current_time()}]----搜索关键词:{self.search_key}----点击了{self.click_counts}个商品")
- return
- time.sleep(self.get_sleep_time())
- spider_no += 1
- except Exception as e:
- print(f'采集药品详情数据出错:{e}')
- self.loggerPdd.error(f'采集药品详情数据出错:{e}')
- if not self.distinct_target():
- for i in range(1):
- self.swipe_back(1)
- # 最外部有个列表按钮
- if self.distinct_target():
- break
- if i == 0 and not self.distinct_target():
- print('页面出错,退出采集')
- return
- else:
- continue
- if self.d(textStartsWith="抱歉,没有更多商品啦~").exists:
- print('已经到达列表页最底部')
- break
- print('开始滑入下一页')
- # search_list = self.d.xpath('//*[@resource-id="android:id/content"]/android.widget.FrameLayout[1]/android.widget.FrameLayout[1]/android.widget.FrameLayout[1]/android.widget.FrameLayout[1]/android.widget.FrameLayout[1]/android.widget.FrameLayout[1]/android.support.v7.widget.RecyclerView[1]').info
- # bounds = search_list['bounds']
- # try:
- # top = drug_lis[0].info['bounds']['top']
- # except Exception as e:
- # print(f'获取滑动参数top出错:{e}')
- # top = 250
- # search_list = self.d.xpath('//android.support.v7.widget.RecyclerView').info
- # bottom = search_list['bounds']['bottom']
- # end_y = 1400 + top - bottom + 162
- # if end_y < 150:
- # end_y = 150
- end_y = 300
- # self.d.swipe(200, 1400, 200, 1400 + bounds['top'] - bounds['bottom'] + 162, 0.4)
- self.d.swipe(200, 1400, 200, end_y, 0.4)
- time.sleep(self.get_sleep_time())
- def unitest(self):
- """
- 单元测试
- :return:
- """
- # device_id = '21885f5'
- # # self.connect_devices(device_id)
- # # self.screenshot_the_business_license()
- # # cropped_screenshot_path = 'cropped_screenshot.png'
- # # self.get_ocr_res(cropped_screenshot_path)
- # shop_name = '我的店铺'
- # base_path = r'D:\work\dfwy_spider\drug_data\pdd\screenshot'
- # cropped_screenshot_path = os.path.join(base_path, shop_name + '.png')
- # os.makedirs(base_path, exist_ok=True)
- # print(cropped_screenshot_path)
- # cropped_screenshot_path = 'D:\\work\\dfwy_spider\\drug_data\\pdd\\screenshot\\' + shop_name + '.png'
- # print(cropped_screenshot_path)
- # time.sleep(10000)
- ocr_res = self.get_ocr_res('ceshi1.jpg')
- print(f'ocr_res:{ocr_res}')
- # 获取当前时间
- current_time = datetime.datetime.now()
- # 格式化为时分秒
- time_str = current_time.strftime("%H-%M-%S")
- # 生成随机的 8 位字符串
- random_str = secrets.token_hex(4) # 生成 4 个字节的随机字符串,转换为 8 位十六进制字符串
- screenshot_path = 'instructionscreenshot1-' + time_str + '-' + random_str + '.png'
- print(screenshot_path)
- # if ocr_res:
- # for item in ocr_res:
- # if '拖动滑块完成' in item['words']:
- # print("滑块验证")
- # break
- # print("ocr_res end")
- # company_name = ''
- # reg_number = ''
- # address = ''
- # if ocr_res:
- # for item in ocr_res:
- # if '企业注册号' in item['words']:
- # # print('come in 111')
- # reg_number = item['words'].split(':', 1)[1].strip()
- # elif '企业名称' in item['words']:
- # # print('come in 222')
- # company_name = item['words'].split(':', 1)[1].strip()
- # elif '所:' in item['words']:
- # # print('come in 333')
- # address = item['words'].split(':', 1)[1].strip()
- # # 输出结果
- # print("企业注册号:", reg_number)
- # print("企业名称:", company_name)
- # print("住所:", address)
- # screenshot_verify_path = 'screenshot_verify.png'
- # img = cv2.imread(screenshot_verify_path)
- # # 指定裁剪区域 (left, top, right, bottom)
- # left = 118
- # top = 478
- # right = 602
- # bottom = 722
- # cropped_verify_img = img[top:bottom, left:right]
- # cropped_verify_creenshot_path = 'cropped_verify_screenshot.png'
- # cv2.imwrite(cropped_verify_creenshot_path, cropped_verify_img)
- # print('裁剪完成')
- time.sleep(100000)
- title_info = '云南白药 参苓健脾胃颗粒10袋 补脾健胃利湿止泻 脾胃虚弱 饮食不消 或泻或吐 形瘦色萎 神疲乏力 5盒装(补脾健胃)'
- min_price = 85
- shop = '堂鹭北大药房旗舰店'
- scrape_date = '2025-03-19'
- dup_data = {'product': title_info, 'min_price': min_price, 'shop': shop, 'scrape_date': scrape_date}
- print(self.data_is_exists(dup_data))
- #pdd
- def main():
- #999感冒清热颗粒、 三九胃泰颗粒
- #暂时不需要的:
- # '999小儿止咳糖浆'
- # '999小儿氨酚黄那敏颗粒'
- # '999小儿感冒颗粒'
- # '999抗病毒口服液10ml*6支'
- # '今维多赐多康牌蛋白粉',
- # '必无忧盐酸特比萘芬喷雾剂30ml'
- # '999冰连清咽'
- # '999复方苦参肠炎康片12片'
- # '999强力枇杷露16袋'
- # '999三蛇胆川贝膏138'
- # '999维生素E.C颗粒9袋'
- # '三九胃泰养胃舒颗粒8袋'
- # '999止泻利颗粒15g*8'
- # '史达功右美沙芬愈创甘油醚糖浆120'
- # '999复方氨酚烷胺胶囊6粒'
- # '999可调式生理性海水鼻腔喷雾50'
- # '999小儿止咳糖浆120' #不低于19.8
- # '999小儿止咳糖浆225' #禁止挂网
- # '999小儿感冒颗粒6g*10' #不低于24.9
- # '999小儿感冒颗粒6g*24' #禁止挂网
- # '999小儿氨酚黄那敏颗粒6g*10袋' #不低于15.8
- # '999小儿氨酚黄那敏颗粒6g*20袋' #禁止挂网
- # '999小儿咽扁颗粒8g*10袋' #仅限999官旗店
- # '999阿奇霉素片'
- #OTC
- # '999银菊清咽颗粒' #没有数据
- # '999感冒清热颗粒6g*10'
- # '999选平硝酸咪康唑乳膏20g'
- # '999糠酸莫米松乳膏10g'
- # '999表虚感冒颗粒' #没有数据
- # '999补脾益肠丸'
- # '999壮骨关节胶囊'
- # '999壮骨关节丸6g*20'
- # '999正天丸6g*15'
- # '999正天胶囊'
- # '三九胃泰胶囊'
- # '三九胃泰颗粒20g*10'
- # '三九胃泰颗粒2.5g*6'
- # '999藿香正气合剂10ml*6',
- # '999藿香正气合剂10ml*10',
- # '999黄芪精',
- # '999曲安奈德益康唑乳膏30g',
- # '999葡萄糖酸锌口服溶液',
- # '佳美舒阿奇霉素肠溶胶囊4'
- # '三九复方金银花颗粒10g*8袋'
- # '999维生素C咀嚼片'
- # '999强力枇杷露150ml'
- # '999强力枇杷露' #同时支持120,150和225ml
- # '顺峰酮康他索乳膏' #包含10g和20g两个规格 10g 不低于7.5 20g 不低于12.5 '顺峰康王酮康他索乳膏'
- # '999板蓝根颗粒10g*20' #不低于26.9
- # '999复方氨酚烷胺胶囊12粒' #不低于17.9 #统一成:999复方氨酚烷胺胶囊
- # '999复方氨酚烷胺胶囊10粒' #禁止挂网 #统一成:999复方氨酚烷胺胶囊
- # '999复方氨酚烷胺胶囊6粒' #禁止挂网 #统一成:999复方氨酚烷胺胶囊
- # '999咽炎片0.26g*12片' #不低于13.5 #999咽炎片0.26g*12片*2板改成 999咽炎片0.26g*12片
- # '999荆防颗粒' #美团没有数据 #禁止挂网 拼多多也没数据
- # '999小儿感冒宁颗粒' #禁止挂网 999小儿感冒宁颗粒2.5g*10袋 改成 999小儿感冒宁颗粒
- # '999感冒灵颗粒10g*9袋' #不低于15.5
- # '999皮炎平复方醋酸地塞米松乳膏20' #不低于12.5
- # '三九胃泰颗粒20g*6袋' #不低于13.5
- # '999复方氨酚烷胺胶囊'
- # '999感冒灵胶囊' #仅限999官旗店
- # '速复康磷酸奥司他韦胶囊75mg*10' #美团没数据 # 禁止挂网 999磷酸奥司他韦胶囊75mg*10 改成 速复康磷酸奥司他韦胶囊75mg*10
- # '史达功右美沙芬愈创甘油醚糖浆120' #仅限999官旗店
- # '999小儿感冒颗粒6g*10' #不低于24.9
- # '999抗病毒口服液',
- # '999蒲地蓝消炎片',
- # '999小柴胡颗粒10g*15',
- # '999复方感冒灵颗粒',
- # '999必无忧盐酸特比萘芬乳膏15'
- # '999复方板蓝根颗粒15g*15袋'
- # '999速复康布洛芬缓释胶囊'
- # '999精氨酸布洛芬颗粒'
- # '999强力枇杷露120ml'
- #2025-08-01最新 其中 藿香正气合剂两种规格 10支和6支 抗病毒口服液 12支和18支 蒲地蓝 24片 36片和44片 枇杷露225ml 小柴胡颗粒9袋和15袋 养胃舒 6袋 复方感冒灵颗粒15袋,
- #曲安奈德益康唑乳膏 30g 葡萄糖酸锌口服溶液 12支 18支 24支和30支,
- # 1、999止泻利颗粒15g*8 没有数据 2、三九胃泰养胃舒颗粒8袋 没有数据 3、999三蛇胆川贝膏138 没有数据 4、999强力枇杷露16袋 没有数据 5、999复方苦参肠炎康片12片 6、999冰连清咽 没有数据
- #############以下是日常采集的品规start##################
- # '三九胃泰养胃舒颗粒10g*10',
- # '999复方感冒灵颗粒',
- # '999感冒清热颗粒12g*18' #禁止挂网
- # '999小儿感冒宁颗粒' #禁止挂网 999小儿感冒宁颗粒2.5g*10袋 改成 999小儿感冒宁颗粒
- # '999小儿咽扁颗粒8g*10袋' #仅限999官旗店
- # '999布洛芬混悬液'
- #########2026春节采集的品规start################################
- # '999藿香正气合剂'
- # '999糠酸莫米松凝胶15',
- # '999抗病毒口服液10ml*10'
- # '999抗病毒口服液10ml*12'
- # '999强力枇杷露225ml',
- # '999糠酸莫米松凝胶10' #不低于26.9
- #########2026春节采集的品规end################################
- ############以下是日常采集的品规start###########################
- #6
- # '999皮炎平复方醋酸地塞米松乳膏20' #不低于12.5 #199
- # '史达功右美沙芬愈创甘油醚糖浆120' # 仅限999官旗店 √#89不用了
- # '999养胃舒颗粒10g*10', #74
- # '史达功右美沙芬愈创甘油醚糖浆180' # 仅限999官旗店 √#不用了
- search_key_list = [
- '999小儿止咳糖浆100',
- '999养胃舒颗粒10g*10',
- '999皮炎平复方醋酸地塞米松乳膏20',
- ]
- # 切 本程序不执行以下品规
- # '史达功右美沙芬愈创甘油醚糖浆120ml' # 仅限999官旗店
- # '史达功右美沙芬愈创甘油醚糖浆180ml' # 仅限999官旗店
- # '999强力枇杷露120ml'
- #日常品规采集
- #
- #999糠酸莫米松凝胶15
- #999复方感冒灵颗粒14g*15
- # search_key_list = ['999复方感冒灵颗粒'] # 参苓健脾胃颗粒 香砂平胃颗粒 舒肝颗粒 清肺化痰丸
- # 设备序列号
- # device_id = 'e2899b34'
- # device_id = '656DTOPRZDEALZ5X'
- # device_id = '2e58510'
- # device_id = 'ea4e4eb8'
- # device_id = 'IZTOWWDQT45D49BU'
- # device_id = 'INXCDAIR75FMMFGU'
- device_id = 'CMKFUSSG99ROR489'
- # device_id = '95b2c764'
- # device_id = 'UCQGF6CQFMU8WKHI'
- # device_id = 'U8ONIJJJS4CELVD6'
- # device_id = 'OVFETO8PCY45E6A6'
- # device_id = 'IRLZAAQCDMHYWKTS'
- # device_id = 'DEZXWKUC7DJBLVPJ'
- # device_id = 'U47HZDRG8XJBBURW'
- # device_id = 'WWRO9LTGG6KFGQCM'
- # device_id = 'GQIRKB7LVOONM7VW'
- # device_id = 'ZDQWUSSWBEDI896T'
- # device_id = '656DTOPRZDEALZ5X'
- # device_id = 'N7ZXBITOSOGMYXQS'
- # device_id = '1462a51f'
- # device_id = '4TZDUGTOAIFMJVGU'
- # device_id = 'GIOFIBRKZTUGJJAE'
- # device_id = 'fcb3c749'
- search_key_length = len(search_key_list)
- for keyword_idx, search_key in enumerate(search_key_list):
- print(f"正在处理第 {keyword_idx+1}/{len(search_key_list)} 个关键词:{search_key}")
- pdd = PDD(search_key, device_id)
- # pdd.unitest()
- # pdd.main('369dcf96')
- # pdd.main('2e58510')
- pdd.main(device_id, search_key_length, keyword_idx)
- if __name__ == '__main__':
- main()
- # scheduler = BlockingScheduler()
- # scheduler.add_job(main, 'cron', hour=11, minute=1, misfire_grace_time=120)
- # try:
- # scheduler.start()
- # except (KeyboardInterrupt, SystemExit):
- # pass
|