一、背景
- 最近再csdn上写文章才发现17年7月之前没绑定手机号,账号被盗,上面发布了很多垃圾广告,想删除才发现CSDN的回收站没有批量删除功能,只能一条一条的删,甚是麻烦,于是利用python中的selenium库编写个脚本实现批量删除。
二、实现过程
1.chrome的webdriver安装
- URL:http://npm.taobao.org/mirrors/chromedriver/
- 打开链接,找到自己chrome对于版本的chromedriver
-
2.安装selenium库
pip install selenium
3.具体实现
导入如下三个库,webdriver实现网页的点击操作;sleep用于等待,避免网速慢时操作跟不上,从而找不到元素;ActionChains主要用于模拟鼠标悬停再删除菜单上
from selenium import webdriver
from time import sleep
from selenium.webdriver import ActionChains
创建webdriver对象,打开目标网站
# 创建webdriver对象
wd = webdriver.Chrome(
r'D:\ProgramFiles\chromedriver_88_4324_96\chromedriver.exe')
# 调用get方法,打开网址
wd.get('https://mp.csdn.net/console/article')
sleep(1)
模拟登录,思路很简单,按照实际登录过程,一步步找到自己点击元素的位置即可
# 点击账号密码
wd.find_element_by_xpath(
'//*[@id="app"]/div/div/div[1]/div[2]/div[5]/ul/li[2]/a').click()
wd.find_element_by_id('tabOne').click() # 点击账号密码登录
sleep(1)
# 发送用户名
wd.find_element_by_id('all').send_keys('username')
# 发送登录密码
wd.find_element_by_id('password-number').send_keys('password')
# 点击登录按钮
wd.find_element_by_xpath(
'//*[@id="app"]/div/div/div[1]/div[2]/div[5]/div/div[6]/div/button').click()
sleep(1)
查找删除位置,根据实际点击过程一步步找到元素即可。这里的难点主要在怎样选择定位下拉菜单上。
# 查找回收站
wd.find_element_by_xpath('//*[@id="pills-tab"]/li[6]/span').click()
sleep(1)
# 查找删除按钮
ems = wd.find_elements_by_class_name('el-dropdown-selfdefine')
couts=len(ems)
for i in range(couts):
#鼠标悬停在下拉菜单上
ActionChains(wd).move_to_element(ems[i]).perform()
abv = wd.find_element_by_link_text('彻底删除').click()
# 点击确定按钮
wd.find_element_by_xpath(
'/html/body/div[5]/div/div[3]/button[2]').click()
4.完整代码
```python from selenium import webdriver from time import sleep from selenium.webdriver import ActionChains
try:
# 创建webdriver对象
wd = webdriver.Chrome(
r'D:\ProgramFiles\chromedriver_88_4324_96\chromedriver.exe')
# 调用get方法,打开网址
wd.get('https://mp.csdn.net/console/article')
sleep(1)
# 点击账号密码
wd.find_element_by_xpath(
'//*[@id="app"]/div/div/div[1]/div[2]/div[5]/ul/li[2]/a').click()
wd.find_element_by_id('tabOne').click() # 点击账号密码登录
sleep(1)
# 发送用户名
wd.find_element_by_id('all').send_keys('username')
# 发送登录密码
wd.find_element_by_id('password-number').send_keys('password')
# 点击登录按钮
wd.find_element_by_xpath(
'//*[@id="app"]/div/div/div[1]/div[2]/div[5]/div/div[6]/div/button').click()
sleep(1)
# 查找回收站
wd.find_element_by_xpath('//*[@id="pills-tab"]/li[6]/span').click()
sleep(1)
# 查找删除按钮
ems = wd.find_elements_by_class_name('el-dropdown-selfdefine')
couts=len(ems)
for i in range(couts):
#鼠标悬停在下拉菜单上
ActionChains(wd).move_to_element(ems[i]).perform()
abv = wd.find_element_by_link_text('彻底删除').click()
# 点击确定按钮
wd.find_element_by_xpath(
'/html/body/div[5]/div/div[3]/button[2]').click()
print('删除完毕')
except Exception as ex: print(‘errorInfo’, ex) wd.quit() ```
三、小结
- 主要难点在于悬停菜单的选取上,刚开始用select方法试了很多遍行不通;
- 运行过程中容易找不到元素,找不到的地方添加一个sleep(1)等一会即可。