The value of knowledge lies not in possession, but in share.

0%

Python+Selenium实现网页自动化评论

最开始是参与美的冰箱旗舰店的微淘活动,评论参与抽奖,如上图所示。因手动评论太过于枯燥,便想着写一个自动评论的脚本。

搭建Selenium环境

先决条件,已安装好Python3

  1. 安装Selenium

    1
    pip3 install selenium
  2. 安装Chromedriver

    Chromedriver下载地址:http://chromedriver.storage.googleapis.com/index.html

    根据自己Chrome浏览器的版本下载对应的Chromedriver, 我的版本如下:

    1
    sudo cp -r chromedriver /usr/local/bin/
  3. 测试安装效果

    test.py
    1
    2
    3
    4
    5
    6
    7
    from selenium import webdriver

    browser = webdriver.Chrome()

    browser.get("http://www.baidu.com")
    print(browser.page_source)
    browser.close()

    运行:

    1
    python test.py

在已打开的浏览器中进行Selenium控制

  1. 找到本地安装的浏览器启动路径,例如Chrome:

    1
    2
    3
    4
    # For Mac
    /Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome
    # For Win
    C:\Program Files (x86)\Google\Chrome\Application\chrome.exe
  2. 通过命令行启动ChromeDbug模式

    1
    2
    3
    4
    # For Mac
    /Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome -remote-debugging-port=9222
    # For Win
    C:\Program Files (x86)\Google\Chrome\Application>chrome.exe --remote-debugging-port=9222
  3. 连接调试开关打开的Chrome

    1
    2
    3
    options = webdriver.ChromeOptions()
    options.debugger_address = '127.0.0.1:9222'
    browser = webdriver.Chrome(options=options)

根据页面标签写脚本

DeBugs

处理弹窗确认

评论成功后,页面会提示“回复成功”,并等待确认。

关于Selenium对弹窗的处理,参考了此篇文章:selenium对弹窗(alert)的处理

不过,在处理弹窗确认的这一步,出现报错Message: no such alert

1
2
3
4
5
6
7
8
9
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException

wait = WebDriverWait(driver, 10)
wait.until(EC.alert_is_present())

alert = driver.switch_to.alert
alert.accept()

解决方案参考:https://stackoverflow.com/questions/33466853/switch-to-alert-text-not-working

评论后没有提交

经过测试,发现是评论一下一步提交操作之间的时间过短,适当增加延时。

🍭支持一根棒棒糖吧!