selenium

一 selenium基本使用

# requests 发送请求,不能加载ajax 
# selenium:直接操作浏览器,不是直接发送http请求,而是用代码控制模拟人操作浏览器的行为,js会自动加载
# requests和selenium谁的效率高?requests的效率更高。requests可以开多线程去爬取数据,而使用selenium开多线程,就相当于开了多个浏览器,谷歌浏览器,一个页面标签就是一个进程。所以效率比较低。

# appnium :直接操作手机

# 使用步骤(操作什么浏览器:1 谷歌(为例) 2 ie 3 Firefox)
	1 下载谷歌浏览器驱动(跟浏览器版本一致)
    	-https://registry.npmmirror.com/binary.html?path=chromedriver/
        -浏览器版本:114.0.5735.199
        -驱动版本对应
        -放到项目路径下
       

1.1 基本使用

# pip3.8 install selenium
from selenium import webdriver
import time
# webdriver.浏览器名
# 1.打开浏览器
chrome = webdriver.Chrome()  # 新版本不需要下载驱动
# 2.只能给浏览器发get请求,只有点击,才会触发post请求
chrome.get('https://www.baidu.com')
time.sleep(10)
# 3.关闭浏览器
chrome.close()

1.2 百度搜索

from selenium import webdriver
from selenium.webdriver.common.by import By  # 按照什么方式查找,By.ID,By.CSS_SELECTOR
import time

# webdriver.浏览器名
# 1.打开浏览器
chrome = webdriver.Chrome()
# 2.发get请求
chrome.get('https://www.baidu.com')
time.sleep(1)

# 3.寻找输入框,有id优先使用id找
input_name = chrome.find_element(by=By.ID, value='kw')
# 往标签中写内容
input_name.send_keys('狗狗图片')

# 4.寻找按钮
button = chrome.find_element(By.ID, 'su')
# 点击按钮
button.click()
time.sleep(3)

# 5.关闭浏览器
chrome.close()

1.3 模拟登录百度

from selenium import webdriver
from selenium.webdriver.common.by import By
import time

# 1.打开浏览器
chrome = webdriver.Chrome()
# 2.发get请求
chrome.get('https://www.baidu.com')
time.sleep(1)
chrome.implicitly_wait(10)  # 隐士等待---> 找标签,如果找不到就先等,等10s,如果10s内,标签有了,直接往下执行,如果登录10s还没有,就报错
# 全屏
chrome.maximize_window()
time.sleep(2)

# 3.寻找登录,如果是a标签,可以根据a标签文字找,链接文字
submit_login = chrome.find_element(By.LINK_TEXT, '登录')
submit_login.click()

# 点击短信登录
sms_login = chrome.find_element(By.ID, 'TANGRAM__PSP_11__changeSmsCodeItem')
sms_login.click()
time.sleep(1)

# 转到账号登录
username_login = chrome.find_element(By.ID, 'TANGRAM__PSP_11__changePwdCodeItem')
username_login.click()
time.sleep(1)

# 4.输入用户名和密码
username = chrome.find_element(By.ID, 'TANGRAM__PSP_11__userName')

username.send_keys('15981392337')
password = chrome.find_element(By.ID, 'TANGRAM__PSP_11__password')
password.send_keys('zhenga1997')

login_btn = chrome.find_element(By.ID, 'TANGRAM__PSP_11__submit')
time.sleep(1)
login_btn.click()

time.sleep(3)

# 5.关闭浏览器
chrome.close()

二 selenium其他用法

2.1 无头

# 无界面浏览器(一堆配置)
import time

from selenium import webdriver
from selenium.webdriver.chrome.options import Options  # 只针对于谷歌浏览器

chrome_options = Options()
chrome_options.add_argument('window-size=1920x3000')  # 指定浏览器分辨率
chrome_options.add_argument('--disable-gpu')  # 谷歌文档提到需要加上这个属性来规避bug
chrome_options.add_argument('--hide-scrollbars')  # 隐藏滚动条, 应对一些特殊页面
chrome_options.add_argument('blink-settings=imagesEnabled=false')  # 不加载图片, 提升速度
chrome_options.add_argument('--headless')  # 浏览器不提供可视化页面. linux下如果系统不支持可视化不加这条会启动失败
# chrome_options.binary_location = r"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"  # 手动指定使用的浏览器位置

chrome = webdriver.Chrome(options=chrome_options)
chrome.get('https://www.baidu.com')

print(chrome.page_source)  # 当前页面内容
time.sleep(3)
chrome.close()  # 切记关闭浏览器,回收资源

2.2 查找标签

from selenium import webdriver
from selenium.webdriver.common.by import By

bro = webdriver.Chrome()  # 打开了浏览器
bro.get('https://www.cnblogs.com/')
bro.implicitly_wait(10)

# bs4 find和find_all 也支持css

# selenium find_element和find_elements
# find_element:找一个
# find_elements:找所有
bro.find_element(by=By.ID)  # 根据id号找一个
bro.find_element(by=By.NAME)  # 根据name属性找一个
bro.find_element(by=By.TAG_NAME, value='div')  # 根据标签名找
bro.find_element(by=By.LINK_TEXT)  # 根据a标签文字
bro.find_element(by=By.PARTIAL_LINK_TEXT)  # 根据a标签文字模糊找
bro.find_element(by=By.CLASS_NAME)  # 根据类名

# find_element和find_elements也支持css和xpath
bro.find_element(by=By.CSS_SELECTOR)  # 根据css选择器找
bro.find_element(by=By.XPATH)  # 根据xpath
bro.close()

2.3 获取标签属性

'''
print(tag.get_attribute('src'))  # 用的最多
tag.text  # 文本内容
#获取标签ID,位置,名称,大小(了解)
print(tag.id)
print(tag.location)
print(tag.tag_name)
print(tag.size)
'''

from selenium import webdriver
import time
from selenium.webdriver.common.by import By

chrome = webdriver.Chrome()
chrome.get('https://www.chaojiying.com/apiuser/login/')
chrome.implicitly_wait(10)
# 找验证码标签
tag = chrome.find_element(By.CSS_SELECTOR,
                          'body > div.wrapper_danye > div > div.content_login > div.login_form > form > div > img')


print(tag.get_attribute('src'))  # 拿属性
print(tag.text)  # 拿文本
print(tag.id)  # 不是属性id,是selenum提供的要给id,无用
print(tag.location)  # x  y坐标
print(tag.tag_name)  # 标签,img
print(tag.size)  # 大小
"""
https://www.chaojiying.com/include/code/code.php?u=2

2674CA3EC9A019804B9CCBC9A9221178_element_45
{'x': 670, 'y': 289}
img
{'height': 50, 'width': 180}
"""

三 selenium等待元素加载

# 程序执行速度很快--->获取标签--->标签还没加载好--->直接去拿会报错

# 显示等待:当你要找一个标签的时候,给它加单独加等待时间
# 隐士等待:只要写一行,代码中查找标签,如果标签没加载好,会自动等待
	browser.implicitly_wait(10)

selenium元素操作

# 输入框输入内容,删除内容
	tag.send_keys(写文字)
    tag.clear()
# 按钮点击
	tag.click()

四 selenium执行js

#1 其实在页面中,可能有些变量,全局的,直接可以把变量打印出来
#2 js操作页面
	可以干的事
        -获取当前访问的地址  window.location
        -打开新的标签
        -滑动屏幕-->bro.execute_script('scrollTo(0,document.documentElement.scrollHeight)')
        -获取cookie,获取定义的全局变量

from selenium import webdriver
import time
bro = webdriver.Chrome()
bro.get('https://www.pearvideo.com/')
bro.implicitly_wait(5)

# 执行js,execute_script(js代码)
bro.execute_script('alert(urlMap.loginUrl);')  # 就可以使用三引号传js代码,传值

# 获取当前页面cookie
bro.execute_script('alert(document.cookie)')
# 获取当前页面访问的地址
bro.execute_script('alert(window.location)')


bro.execute_script('scrollTo(0,document.documentElement.scrollHeight)')


time.sleep(5)
bro.close() # 关闭选项卡
bro.quit()  # 关闭所有页面

五 selenium高级操作

5.1 selenium切换选项卡

from selenium import webdriver
import time
bro = webdriver.Chrome()
bro.get('https://www.pearvideo.com/')
bro.implicitly_wait(10)
print(bro.window_handles)
# 开启选项卡
bro.execute_script('window.open()')
# 获取出所有选项卡
print(bro.switch_to.window(bro.window_handles))


bro.switch_to.window(bro.window_handles[1]) # 切换到某个选项卡
bro.get('http://www.taobao.com')

time.sleep(2)
bro.switch_to.window(bro.window_handles[0]) # 切换到某个选项卡
bro.get('http://www.baidu.com')

time.sleep(2)
bro.close() # 关闭选项卡
bro.quit()  # 关闭页面

5.2 selenium前进后退

bro.back()
time.sleep(2)
bro.forward()

5.3 selenium登录cnblogs

# 1 打开cnblogs,点进登录页面,输入用户名密码,点登录(可能会出现验证码)-->手动操作

# 2 登录成功后---->拿到cookie--->保存到本地--->关闭浏览器

# 3 开启selenium,打开浏览器--->把本地的cookie写入到当前浏览器中---->当前浏览器就是登录状态
from selenium import webdriver
from selenium.webdriver.common.by import By
import time
import json

##### 先登录
bro = webdriver.Chrome()
bro.get('https://www.cnblogs.com/')
bro.implicitly_wait(5)
bro.maximize_window()
login_btn = bro.find_element(By.LINK_TEXT, '登录')
login_btn.click()
# time.sleep(2)

# 用户名和密码
username = bro.find_element(By.CSS_SELECTOR, '#mat-input-0')
password = bro.find_element(By.ID, 'mat-input-1')
submit_button = bro.find_element(By.CSS_SELECTOR,
                                 'body > app-root > app-sign-in-layout > div > div > app-sign-in > app-content-container > div > div > div > form > div > button > span.mat-button-wrapper')

username.send_keys('285462828@qq.com')
password.send_keys('zhenga1997')
submit_button.click()

# 有可能出现验证码
input('')  # 手动操作验证码,操作完后,敲回车程序继续执行
time.sleep(2)  # 登录成功了,有cookie了
cookies = bro.get_cookies()
# print(cookies)

# 把cookies保存到本地
'''可以把cookie保存在redis中'''
with open('cnblogs.json', 'w', encoding='utf-8') as f:
    json.dump(cookies, f)

# time.sleep(2)
bro.close()

### 再次打开
bro = webdriver.Chrome()
bro.get('https://www.cnblogs.com/')
bro.implicitly_wait(5)
bro.maximize_window()
# time.sleep(3)
# 本地的cookie,从cookie池中拿的
with open('./cnblogs.json', 'r', encoding='utf-8') as f:
    cookies = json.load(f)
for item in cookies:  # 存起来的是列表套字典,add_cookie是add字典
    print('----', item)
    bro.add_cookie(item)

bro.refresh()  # 刷新页面,刷新完后,就是登录状态
time.sleep(5)
bro.close()

5.4 抽屉半自动点赞

import time
import json

import requests
## 使用selenium登录上去,手动处理验证码
from selenium import webdriver
from selenium.webdriver.common.by import By

bro = webdriver.Chrome()
bro.implicitly_wait(7)
bro.get('https://dig.chouti.com/')

btn_login = bro.find_element(By.ID, 'login_btn')
# btn_login.click()  # 按钮没找到,使用js点击
bro.execute_script("arguments[0].click()", btn_login)
time.sleep(2)

phone = bro.find_element(By.NAME, 'phone')
password = bro.find_element(By.NAME, 'password')
phone.send_keys('18953675221')
password.send_keys('lqz123')
time.sleep(2)
btn_login1 = bro.find_element(By.CSS_SELECTOR, 'body > div.login-dialog.dialog.animated2.scaleIn > div > div.login-footer > div:nth-child(4) > button')
btn_login1.click()

# 可能会出验证码,手动操作
input('你好了吗')
time.sleep(2)
cookies = bro.get_cookies()
print(cookies)
with open('chouti.json', 'w', encoding='utf-8') as f:
    json.dump(cookies, f)
    
time.sleep(2)
bro.close()


### 拿10个要点的新闻
header = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36',
}
# 打开读出cookie
with open('./chouti.json', 'r', encoding='utf-8') as f:
    cookies = json.load(f)
    
# 把selenium拿到的cookie组装成requests能用的cookie
real_cookie = {}
for item in cookies:
    real_cookie[item['name']] = item['value']

print(real_cookie)

res = requests.get('https://dig.chouti.com/top/24hr?_=1689043464339', headers=header).json()
for item in res.get('data'):
    link_id = item.get('id')
    # 缺cookie,如果有了cookie,可以整个页面全点一遍
    data = {
        'linkId': link_id
    }
    res = requests.post('https://dig.chouti.com/link/vote', headers=header, data=data, cookies=real_cookie)
    print(res.text)

    
# 使用requests来点赞用户

六 xpath使用

# 页面中定位元素(标签),两种通用方式
	-css选择器
    -xpath:XPath即为XML路径语言(XML Path Language),它是一种用来确定XML文档中某部分位置的语言
    
    
# xpath语法
    div	选取div标签
    /	从根节点选取
    //	从匹配选择的当前节点选择文档中的节点,而不考虑它们的位置
    .	选取当前节点。
    ..	选取当前节点的父节点。
    @	选取属性

 
doc = '''
<html>
 <head>
  <base href='http://example.com/' />
  <title>Example website</title>
 </head>
 <body>
  <div id='images'>
   <a href='image1.html' id='lqz'>Name: My image 1 <br /><img src='image1_thumb.jpg' /></a>
   <a href='image2.html'>Name: My image 2 <br /><img src='image2_thumb.jpg' /></a>
   <a href='image3.html'>Name: My image 3 <br /><img src='image3_thumb.jpg' /></a>
   <a href='image4.html'>Name: My image 4 <br /><img src='image4_thumb.jpg' /></a>
   <a href='image5.html' class='li li-item' name='items'>Name: My image 5 <br /><img src='image5_thumb.jpg' /></a>
   <a href='image6.html' name='items'><span><h5>test</h5></span>Name: My image 6 <br /><img src='image6_thumb.jpg' /></a>
  </div>
 </body>
</html>
'''
from lxml import etree

html = etree.HTML(doc)
html=etree.parse('search.html',etree.HTMLParser())
# 1 所有节点
a=html.xpath('//*')  # 结果是一个个对象
# 2 指定节点(结果为列表)
a=html.xpath('//head')
# 3 子节点,子孙节点
a=html.xpath('//div/a')
a=html.xpath('//body/a') #无数据
a=html.xpath('//body//a')
# 4 父节点
a=html.xpath('//body//a[@href="image1.html"]/..')
a=html.xpath('//body//a[1]/..')
# 也可以这样
a=html.xpath('//body//a[1]/parent::*')
a=html.xpath('//body//a[1]/parent::div')
# 5 属性匹配
a=html.xpath('//body//a[@href="image1.html"]')

# 6 文本获取     /text()
a=html.xpath('//body//a[@href="image1.html"]/text()')

# 7 属性获取     @属性名
a=html.xpath('//body//a/@href')
# 注意从1 开始取(不是从0)
a=html.xpath('//body//a[1]/@href')

# 8 属性多值匹配
# a 标签有多个class类,直接匹配就不可以了,需要用contains
a=html.xpath('//body//a[@class="li"]')
a=html.xpath('//body//a[contains(@class,"li")]')
a=html.xpath('//body//a[contains(@class,"li")]/text()')

# 9 多属性匹配
a=html.xpath('//body//a[contains(@class,"li") or @name="items"]')
a=html.xpath('//body//a[contains(@class,"li") and @name="items"]/text()')
a=html.xpath('//body//a[contains(@class,"li")]/text()')

# 10 按序选择
a=html.xpath('//a[2]/text()')
a=html.xpath('//a[2]/@href')
# 取最后一个
a=html.xpath('//a[last()]/@href')
a=html.xpath('//a[last()-1]/@href') # 倒数第二个
# 位置小于3的
a = html.xpath('//a[position()<3]/@href')
# 倒数第三个
a=html.xpath('//a[last()-2]/@href')

# 11 节点轴选择
# ancestor:祖先节点
# 使用了* 获取所有祖先节点
a=html.xpath('//a/ancestor::*')
# 获取祖先节点中的div
a=html.xpath('//a/ancestor::div')
# attribute:属性值
a=html.xpath('//a[1]/attribute::*')
a=html.xpath('//a[1]/attribute::href')

# child:直接子节点
a=html.xpath('//a[1]/child::*')
# descendant:所有子孙节点
a=html.xpath('//a[6]/descendant::*')
# following:当前节点之后所有节点
a=html.xpath('//a[1]/following::*')
a=html.xpath('//a[1]/following::*[1]/@href')
# following-sibling:当前节点之后同级节点
a=html.xpath('//a[1]/following-sibling::*')
a=html.xpath('//a[1]/following-sibling::a')
a=html.xpath('//a[1]/following-sibling::*[2]')
a=html.xpath('//a[1]/following-sibling::*[2]/@href')

print(a)


'''
/
//
.
..
取文本  /text()
取属性  /@属性名
根据属性过滤  [@属性名=属性值]
class 特殊  [contains(@class,"li")]
'''


# 终极大招:复制

七 动作链

# 模拟鼠标点住,拖动的效果,实现滑块认证

# 两种形式
	-形式一:
        actions=ActionChains(bro) #拿到动作链对象
        actions.drag_and_drop(sourse,target) #把动作放到动作链中,准备串行执行
        actions.perform()
    -方式二:
    	ActionChains(bro).click_and_hold(sourse).perform()
    	distance=target.location['x']-sourse.location['x']
        track=0
        while track < distance:
            ActionChains(bro).move_by_offset(xoffset=2,yoffset=0).perform()
            track+=2

实例

from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.support.wait import WebDriverWait  # 等待页面加载某些元素
import time
from selenium.webdriver.common.by import By

driver = webdriver.Chrome()
driver.get('http://www.runoob.com/try/try.php?filename=jqueryui-api-droppable')
driver.implicitly_wait(3)
driver.maximize_window()

try:
   # 页面中又写了一个页面
driver.switch_to.frame('iframeResult')  ##切换到iframeResult
    sourse = driver.find_element(By.ID, 'draggable')
    target = driver.find_element(By.ID, 'droppable')

    # 方式一:基于同一个动作链串行执行
    # actions = ActionChains(driver)  # 拿到动作链对象
    # actions.drag_and_drop(sourse, target)  # 把动作放到动作链中,准备串行执行
    # actions.perform()

    # 方式二:不同的动作链,每次移动的位移都不同
    ActionChains(driver).click_and_hold(sourse).perform()  # 鼠标点中源标签 不松开
    distance=target.location['x']-sourse.location['x']  # 差的距离

    track = 0
    while track < distance:
        ActionChains(driver).move_by_offset(xoffset=5, yoffset=0).perform()
        track += 5
    ActionChains(driver).release().perform()  # 释放鼠标
    time.sleep(10)

finally:
    driver.close()

    
# 滑块验证,需要先查出缺口的位置

自动登录12306

import time
from selenium.webdriver import ActionChains
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options

# 12306检测到咱们用了自动化测试软件
options = Options()
options.add_argument("--disable-blink-features=AutomationControlled")  # 去掉自动化控制检测
bro = webdriver.Chrome(chrome_options=options)
bro.get('https://kyfw.12306.cn/otn/resources/login.html')
bro.implicitly_wait(5)
bro.maximize_window()

user_login = bro.find_element(By.CSS_SELECTOR,
                              '#toolbar_Div > div.login-panel > div.login-box > ul > li.login-hd-code.active > a')
user_login.click()
time.sleep(1)

# 用户名和密码
username = bro.find_element(By.ID, 'J-userName')
password = bro.find_element(By.ID, 'J-password')
submit_btn = bro.find_element(By.ID, 'J-login')
username.send_keys('18953675221')
password.send_keys('')
time.sleep(3)
submit_btn.click()

time.sleep(5)

# 找到滑块
span = bro.find_element(By.ID, 'nc_1_n1z')
# 滑动滑块
ActionChains(bro).click_and_hold(span).perform()
ActionChains(bro).move_by_offset(xoffset=300, yoffset=0).perform()
ActionChains(bro).release().perform()
time.sleep(5)

bro.close()

八 打码平台

# 以后会遇到验证码-
	-简单的数字字母
    -高级一些的,计算题,成语
    -选中图中的  公交车
    ...
    
    
# 第三方解决方法:打码平台--->你验证码图片传给它,它给你破解,回给你,花钱

# 超级鹰
3053345678
lqz123

-价格体系
-开发文档
	# 下载python的dom
    # 把两个复制到项目中

8.1 打码平台自动登录

import time

from selenium import webdriver
from selenium.webdriver.common.by import By
from chaojiying import ChaojiyingClient
from PIL import Image
bro = webdriver.Chrome()
bro.get('http://www.chaojiying.com/apiuser/login/')
bro.implicitly_wait(10)
bro.maximize_window()
try:
    username = bro.find_element(by=By.XPATH, value='/html/body/div[3]/div/div[3]/div[1]/form/p[1]/input')
    password = bro.find_element(by=By.XPATH, value='/html/body/div[3]/div/div[3]/div[1]/form/p[2]/input')
    code = bro.find_element(by=By.XPATH, value='/html/body/div[3]/div/div[3]/div[1]/form/p[3]/input')
    btn = bro.find_element(by=By.XPATH, value='/html/body/div[3]/div/div[3]/div[1]/form/p[4]/input')
    username.send_keys('306334678')
    password.send_keys('lqz123')

    # 获取验证码:
    # 1 整个页面截图,保存在本地
    bro.save_screenshot('main.png')
    # 2 使用pillow,从整个页面中截取出验证码图片 code.png
    img = bro.find_element(By.XPATH, '/html/body/div[3]/div/div[3]/div[1]/form/div/img')
    location = img.location
    size = img.size
    print(location)
    print(size)

    # 使用pillow扣除大图中的验证码
    img_tu = (int(location['x']), int(location['y']), int(location['x'] + size['width']), int(location['y'] + size['height']))
    # 抠出验证码
    #打开
    img = Image.open('./main.png')
    # 抠图
    fram = img.crop(img_tu)
    # 截出来的小图
    fram.save('code.png')

	# 调用超级鹰
    chaojiying = ChaojiyingClient('3053345678', 'lqz123', '950575')	#用户中心>>软件ID 生成一个替换 96001
    im = open('code.png', 'rb').read()
    print(chaojiying.PostPic(im, 1902))  # 1902 验证码类型  官方网站>>价格体系 3.4+版 print 后要加()
    res_code=chaojiying.PostPic(im, 1902)['pic_str']
    code.send_keys(res_code)
    time.sleep(5)
    btn.click()
    time.sleep(10)
except Exception as e:
    print(e)

finally:
    bro.close()
   

练习:selenium爬取京东商品信息

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.keys import Keys  # 键盘按键操作
import time

# 获取商品的函数
def get_goods(bro):
    # 往下滑动一下屏幕
    bro.execute_script('scrollTo(0,5000)')

    # 获取商品的信息
    goods = bro.find_elements(By.CLASS_NAME, 'gl-item')
    # from selenium.webdriver.remote.webelement import WebElement是每个获取出来的元素的所属类

    # print(len(goods))
    for good in goods:
        try:
            name = good.find_element(By.CSS_SELECTOR, 'div.p-name>a').text
            price = good.find_element(By.CSS_SELECTOR, 'div.p-price>strong>i').text
            url = good.find_element(By.CSS_SELECTOR, 'div.p-img>a').get_attribute('href')
            commit_num = good.find_element(By.CSS_SELECTOR, 'div.p-commit a').text
            img = good.find_element(By.CSS_SELECTOR, 'div.p-img img').get_attribute('src')
            if not img:
                img = 'https:' + good.find_element(By.CSS_SELECTOR, 'div.p-img img').get_attribute('data-lazy-img')
            print('''
                商品名字:%s
                商品价格:%s
                商品评论数:%s
                商品图片:%s
                商品链接:%s
                ''' % (name, price, commit_num, img, url))
            
            # 把数据保存到MySQL中
        except Exception as e:
            print(e)
            continue

        # 找出下一页按钮,点击
    next = bro.find_element(By.PARTIAL_LINK_TEXT, '下一页')
    next.click()
    get_goods(bro)  # 递归调用


options = Options()
options.add_argument("--disable-blink-features=AutomationControlled")  # 去掉自动化控制
bro = webdriver.Chrome(options=options)

bro.get('https://www.jd.com/')
bro.maximize_window()
bro.implicitly_wait(10)

try:
    search_key = bro.find_element(By.ID, 'key')
    search_key.send_keys('mac pro')
    search_key.send_keys(Keys.ENTER)  # 回车
    # search_key.send_keys(Keys.BACKSPACE)  # 键盘,退回
    get_goods(bro)
except Exception as e:
    print(e)
finally:
    bro.close()
posted @ 2023-08-07 21:49  星空看海  阅读(46)  评论(0编辑  收藏  举报