Python Selenium 自动登入1688

Python Selenium是一个用于自动化Web浏览器操作的库。它提供了一组功能强大的工具和API,可以模拟用户在浏览器中的行为,并执行各种任务,如点击、输入文本、提交表单等。

要使用Python Selenium登录1688网站,需要进行以下步骤:

  1. 安装Selenium库:在Python环境中,可以使用pip命令安装Selenium库。

    python 复制代码
    pip install selenium
  2. 下载并配置浏览器驱动程序:Selenium需要一个特定的浏览器驱动程序来与浏览器交互。对于Chrome浏览器,可以下载ChromeDriver;对于Firefox浏览器,可以下载geckodriver。将驱动程序放在系统路径中,或者指定其路径。

  3. 导入必要的模块:在Python脚本中,首先要导入selenium模块,以及WebDriver对象(用于控制浏览器)和Keys对象(用于模拟键盘输入)。

    python 复制代码
    from selenium import webdriver
    from selenium.webdriver.common.action_chains import ActionChains
    from selenium.webdriver.common.by import By
  4. 创建WebDriver实例:根据使用的浏览器类型,创建相应的WebDriver实例。例如,对于Chrome浏览器:

    python 复制代码
    driver = webdriver.Chrome()
  5. 打开1688网站:使用WebDriver打开1688网站的登录页面。

    python 复制代码
    driver.get("https://www.1688.com/")
  6. 定位并输入登录凭据:使用WebDriver的find_element方法找到用户名和密码的输入框,并使用send_keys方法输入相应的凭据。

  7. 提交登录表单:使用WebDriver的submit方法提交登录表单。

以下是完整代码:

python 复制代码
import time
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.by import By

print('使用selenium模拟登陆')
# 使用selenium模拟登陆,获取并返回cookie
username = ''
password = ''
options = webdriver.ChromeOptions()  # 声明浏览器的对象
options.add_experimental_option('excludeSwitches', ['enable-automation'])
options.add_argument('--disable-blink-features')
options.add_argument('--disable-blink-features=AutomationControlled')  # 去除浏览器selenium监控
#options.add_argument('--headless')  # 浏览器不提供可视化页面
options.add_argument('--disable-gpu')  # 禁用GPU加速
browser = webdriver.Chrome(options=options)
browser.get('https://login.1688.com/')
time.sleep(1)
browser.find_element(By.XPATH, '//*[@id="fm-login-id"]').send_keys(username)
time.sleep(1)
browser.find_element(By.XPATH, '//*[@id="fm-login-password"]').send_keys(password)
time.sleep(1)
browser.find_element(By.XPATH, '//*[@type="submit"]').click()
time.sleep(4)
# 检查是否出现了滑动验证码
try:
    slider = browser.find_element(By.XPATH,  '//*[@id="nc_1_n1z"]')
    ActionChains(browser).click_and_hold(slider).perform()  # 按住滑块
    ActionChains(browser).move_by_offset(300, 0).perform()  # 移动到最右边
    ActionChains(browser).pause(0.5).release().perform()  # 松开鼠标
except:
    pass
# cookies_dict = {cookie['name']: cookie['value'] for cookie in driver.get_cookies()}
# driver.quit()
# print(cookies_dict)
相关推荐
鸡哥爱技术9 小时前
Django入门笔记
笔记·python·django
猫耳君9 小时前
汽车网络安全 CyberSecurity ISO/SAE 21434 测试之一
python·安全·网络安全·汽车·iso/sae 21434·cybersecurity
勘察加熊人9 小时前
python将pdf转txt,并切割ai
数据库·python·pdf
IMER SIMPLE10 小时前
人工智能-python-深度学习-神经网络VGG(详解)
人工智能·python·深度学习
Dersun10 小时前
python学习进阶之异常和文件操作(三)
开发语言·python·学习·json
Juchecar10 小时前
通过“单词补全”演示 Transformer 原理(Python代码可运行)
人工智能·python
c8i11 小时前
关于python中的钩子方法和内置函数的举例
python
动能小子ohhh11 小时前
AI智能体(Agent)大模型入门【2】--基于llamaindx部署本地的聊天模型。
人工智能·python·aigc·ai编程
MediaTea11 小时前
Python 第三方库:SymPy(符号计算工具)
开发语言·python·数学建模
Goona_11 小时前
PyQt数字转大写金额GUI工具开发及财务规范实现
python·小程序·交互·pyqt