web.Whatsapp 无头地使用 phantomjs

web.Whatsapp headlessly using phantomjs

使用 Phantomjs 在 web.whatsapp.com 上启动网络会话,使用 chrome 的用户代理作为 whatsapp 不支持 phantomjs 作为用户代理

代码如下:

var page = require('webpage').create();
    page.settings.userAgent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36';
    page.viewportSize = {
      width: 1200,
      height: 800
    };
    page.open('https://web.whatsapp.com/', function() {
      page.render('home.png');
      phantom.exit();
    });

但输出是中间有点的空白屏幕

script output screenshot

我的代码中有任何错误或是否存在任何兼容问题?

Phantomjs 没有等待页面完全加载,您可以看到弹性加载页面图标。

睡眠时尝试此代码。

from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

user_agent = (
    "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36"
)

dcap = dict(DesiredCapabilities.PHANTOMJS)
dcap["phantomjs.page.settings.userAgent"] = user_agent

driver = webdriver.PhantomJS(desired_capabilities=dcap, executable_path=r'/bin/phantomjs')


driver.get('http://web.whatsapp.com')
timeout = 30
try:
    element_present = EC.presence_of_element_located((By.Class, 'qrcode'))
    WebDriverWait(driver, timeout).until(element_present)
except TimeoutException:
    print "Timed out waiting for page to load" 

注意:whatsapp 需要 cryptoSha256 和 cryptoAesCbc 支持的浏览器才能进行正确的加密管理,Phantom js 不支持 cryptoSha256 和 cryptoAesCbc。