通过文本文件

时间:2017-06-29 06:57:29

标签: python selenium-webdriver selenium-chromedriver

我希望我的for循环逐个获取URL并点击并执行一些操作,例如,[点击按钮并提取文本]第一次当URL被点击时需要uname,pwd和登录从下次开始不需要凭据,它可以直接点击按钮并提取网址。

操作代码:用于点击和解压缩工作正常。只有for循环有一些问题

 def lookup(driver,uname,pwd):
    with open("A.txt") as f:
        for line in f:
            url = line.strip()
            print("Getting %s" % url)
            driver.get(url)
            box = driver.wait.until(EC.presence_of_element_located((By.NAME, "j_username")))
            box.send_keys(uname)
            box = driver.wait.until(EC.presence_of_element_located((By.NAME, "j_password")))
            box.send_keys(pwd)
            button = driver.wait.until(EC.element_to_be_clickable((By.NAME, "login")))
            button.click()
            button = driver.wait.until(EC.presence_of_element_located((By.ID, "fetchCandidateChanges_0")))
            button.click()
            driver.wait = WebDriverWait(driver, 15)
            time.sleep(15)
            labels = driver.find_elements_by_xpath('//label[@class="pagebanner"]')
            for label in labels:
                print (label.text)

2 个答案:

答案 0 :(得分:1)

如果每行包含一个URL:

def lookup(driver,uname,pwd):
    with open("A.txt") as f:
        for line in f:
            url = line.strip()  # to remove the trailing \n
            print("Getting %s" % url)
            driver.get(url)

for循环将迭代文件的行。

答案 1 :(得分:1)

  1. read()将整个文件作为单个字符串读取,因此content是字符串"url1\nurl2\url3"

  2. driver.get("content")您可以将文件内容分配给content,但将字符串"content"传递给getcontent"content" 相同的事情。

  3. 相反,您应该逐行阅读文件并将每个网址传递给get

    def lookup(driver, uname, pwd):
        with open("A.txt") as f:
            urls = f.readlines()
        for url in urls:
            print(url)
            driver.get(url)
    

    def lookup(driver, uname, pwd):
        with open("A.txt") as f:
            for url in f:
                print(url)
                driver.get(url)
    

    我通常倾向于选择第一种风格,因为它不会不必要地打开文件。