Python 使用命令行安排

Python schedule with commandline

我有这个问题,我想自动执行一个脚本。 在过去的项目中,我为此使用了 python 调度程序。但是对于这个项目,我不确定如何处理。

问题是该代码使用代码之外的登录详细信息并在启动脚本时在命令行中输入。

例如。 python scriptname.py 邮箱@youremail.com 密码

如何使用 python 调度程序自动执行此操作? 'scriptname.py' 中的代码是:

//LinkedBot.py
import argparse, os, time
import urlparse, random
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from bs4 import BeautifulSoup

def getPeopleLinks(page):
    links = []
    for link in page.find_all('a'):
        url = link.get('href')
        if url:
            if 'profile/view?id=' in url:
                links.append(url)
    return links

def getJobLinks(page):
    links = []
    for link in page.find_all('a'):
        url = link.get('href')
        if url:       
            if '/jobs' in url:
                links.append(url)
    return links

def getID(url):
    pUrl = urlparse.urlparse(url)
    return urlparse.parse_qs(pUrl.query)['id'][0]


def ViewBot(browser):
    visited = {}
    pList = []
    count = 0
    while True:
        #sleep to make sure everything loads, add random to make us look human.
        time.sleep(random.uniform(3.5,6.9))
        page = BeautifulSoup(browser.page_source)
        people = getPeopleLinks(page)
        if people:
            for person in people:
                ID = getID(person)
                if ID not in visited:
                    pList.append(person)
                    visited[ID] = 1
        if pList: #if there is people to look at look at them
            person = pList.pop()
            browser.get(person)
            count += 1
        else: #otherwise find people via the job pages
            jobs = getJobLinks(page)
            if jobs:
                job = random.choice(jobs)
                root = 'http://www.linkedin.com'
                roots = 'https://www.linkedin.com'
                if root not in job or roots not in job:
                    job = 'https://www.linkedin.com'+job
                browser.get(job)
            else:
                print "I'm Lost Exiting"
                break

        #Output (Make option for this)           
        print "[+] "+browser.title+" Visited! \n("\
            +str(count)+"/"+str(len(pList))+") Visited/Queue)"


def Main():
    parser = argparse.ArgumentParser()
    parser.add_argument("email", help="linkedin email")
    parser.add_argument("password", help="linkedin password")
    args = parser.parse_args()

    browser = webdriver.Firefox()

    browser.get("https://linkedin.com/uas/login")


    emailElement = browser.find_element_by_id("session_key-login")
    emailElement.send_keys(args.email)
    passElement = browser.find_element_by_id("session_password-login")
    passElement.send_keys(args.password)
    passElement.submit()

运行 这个在 OSX 上。

关于代码本身

LinkedIn REST Api

您是否尝试过使用 LinkedIn 的 REST Api 而不是检索繁重的页面、填写某种表格并将其发回?

每当 LinkedIn 更改其页面中的某些元素时,您的代码很容易被破坏。而 Api 是 LinkedIn 与用户之间的合同。

在此处查看https://developer.linkedin.com/docs/rest-api and there https://developer.linkedin.com/docs/guide/v2/concepts/methods

凭据

这样您就不必通过命令行传递您的凭据(尤其是您的密码,通过 history 可以清楚地读取),您应该

  • 使用配置文件(使用您的 Api 密钥)并使用 ConfigParser 读取它(或其他任何内容,具体取决于您的配置文件的格式(json、python, 等等...)
  • 或将它们设置到您的环境变量中。

用于调度

使用 Cron

此外,对于调度部分,您可以使用cron

使用芹菜

如果您正在寻找 100% Python 解决方案,您可以使用优秀的 Celery 项目。检查其 periodic tasks.

我至少可以看到两种不同的自动触发脚本的方法。既然你提到你的脚本是这样启动的:

python scriptname.py email@youremail.com password

表示你从shell开始。正如您想要安排的那样,听起来 Crontab 是一个完美的答案。 (例如参见 [​​=12=])

如果你真的想使用python调度器,你可以使用子进程。

在您的文件中使用 python 调度程序:

import subprocess

subprocess.call("python scriptname.py email@youremail.com password", shell=True)

What is the best way to call a Python script from another Python script?

您可以将参数传递给 python 调度程序。

scheduler.enter(delay, priority, action, argument=(), kwargs={}) Schedule an event for delay more time units. Other than the relative time, the other arguments, the effect and the return value are the same as those for enterabs(). Changed in version 3.3: argument parameter is optional. New in version 3.3: kwargs parameter was added.

>>> import sched, time
>>> s = sched.scheduler(time.time, time.sleep)
>>> def print_time(a='default'):
...     print("From print_time", time.time(), a)
...
>>> def print_some_times():
...     print(time.time())
...     s.enter(10, 1, print_time)
...     s.enter(5, 2, print_time, argument=('positional',))
...     s.enter(5, 1, print_time, kwargs={'a': 'keyword'})
...     s.run()
...     print(time.time())
...
>>> print_some_times()
930343690.257
From print_time 930343695.274 positional
From print_time 930343695.275 keyword
From print_time 930343700.273 default
930343700.276