Selenium 开发, Mac python 版,简单套路 2022

Selenium 开发, Mac python 版,简单套路 2022,第1张

1, 短平快

效果为查看 feed 流,

想看很久以前的,不想要用手滑。

就 Selenium 自动滑到底 15 次

import time

from selenium import webdriver

drive = webdriver.Chrome()
drive.implicitly_wait(15)
drive.maximize_window()
drive.get("https://feeds")
for _ in range(15):
    time.sleep(2)
    drive.execute_script("window.scrollTo(0, document.body.scrollHeight)")
解释:

拿到 Chrome 的实例,隐式等待网页刷新出来

最大化窗口,

开启网页,睡两秒,拉到底一次

( 对应, 网页刷新的网络请求,是异步 *** 作 )

1.1 ,准备工作

a, 没使用 webdriver 中的 Safari,

目前是 Safari 只能开一个进程,

Chrome 能开多个进程,方便很多

b , 下载 chrome 的 webdrive, 放到 bin 文件夹

首先,看 chrome 的版本

chrome 中这样 chrome://version/

这里下载驱动

https://chromedriver.chromium.org/downloads

放到这个路径

/usr/local/bin

2, 例子是 booking.com

也就是 fcc 的视频教程,

简单说下套路,( booking.com 的代码,好像更新了好多 )

例如,大量使用 CSS_SELECTOR 2.1, 选择货币
btn = self.find_element(By.CSS_SELECTOR, 'button[data-tooltip-text*="选择你使用的货币"]')
btn.click()

text*= 一部分内容,通常容错好一些

2.2, 填入人数

btn = self.find_element(By.ID, "xp__guests__toggle")
btn.click()
decrease_btn = self.find_element(By.CSS_SELECTOR, 'button[aria-label="减少成人数量"]')
add_btn = self.find_element(By.CSS_SELECTOR, 'button[aria-label="增加成人数量"]')
valContainer = self.find_element(By.ID, "group_adults")
target = total
while True:
    #  get_attribute, receives a key name,
    #  then it tries to give back the value of whatever the attribute is
    count = valContainer.get_attribute("value")
    if int(count) == target:
        break
    elif int(count) > target:
        decrease_btn.click()
    else:
        add_btn.click()

拿到网站的人数数据,get_attribute("value")

少于目标,就 +

多了,就 -

2.3, 选择星级

star_box = self.driver.find_element(By.CSS_SELECTOR, 'div[data-filters-group="class"]')
for star_val in star_vals:
    star_child = star_box.find_element(By.CSS_SELECTOR, f'div[data-filters-item="class:class={star_val}"]')
    # 感觉, html 上的元素,都可以点击
    star_child.click()

先拿父节点,star_box

再拿子节点,star_child

算是,两级定位

3, booking.com 中的异步处理 3.1 使用上面提到的,sleep 大法

场景是,选完星级,选低价,

filter.apply_star_rating(4, 5)
time.sleep(5)
filter.sort_by_price_lowest_first()

如果不 sleep 下,价格排序,一般会把星级筛选,覆盖

3.2, web drive 刷新

场景是,完成筛选和排序的网络请求后,拿到最新的 html

drive.apply_filtrations()
# a workaround to let our bot to grab the data properly
drive.refresh()
drive.report_results()

点击星级筛选,价格排序,等待网页的网络请求刷新,

先刷新,

再去拿最新的 html

4,命令行辅助

mac 上,开启了很多 Chrome 实例,

怎么关?

kill -9 $(ps -x | grep "Google Chrome" | awk "{print }")
5, github repo 5.1 python 语法,传递多参数

函数定义

def apply_star_rating(self, *star_vals):

调用

filter.apply_star_rating(4, 5)

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/918132.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-16
下一篇 2022-05-16

发表评论

登录后才能评论

评论列表(0条)

保存