Python Selenium driver.get()在for循环中不起作用

时间:2018-10-28 13:29:47

标签: python selenium selenium-webdriver

下面的代码登录到一个YouTube帐户,登录后,它应该访问一些YouTube视频。

问题是:

  • 如果我像这里那样做一个简单的直接链接,它就会起作用

    driver.get('https://www.youtube.com/watch?v=FFDDN1C1MEQ')

  • 如果我循环访问多个链接,则会收到错误消息:

    raise exception_class(message, screen, stacktrace)

    InvalidArgumentException: invalid type: sequence, expected a string at line 1 column 8

完整代码如下

import time
import numpy as np
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import NoSuchElementException


def youtube_login():

    email = 'email@email.com'
    password = 'emailPassword'

        # Browser
    driver = webdriver.Firefox()
    driver.get('https://accounts.google.com/ServiceLogin?hl=en&continue=https%3A%2F%2Fwww.youtube.com%2Fsignin%3Fhl%3Den%26feature%3Dsign_in_button%26app%3Ddesktop%26action_handle_signin%3Dtrue%26next%3D%252F&uilel=3&passive=true&service=youtube#identifier')

        # log in
    driver.find_element_by_id('identifierId').send_keys(email)
    driver.find_element_by_class_name('CwaK9').click()
    WebDriverWait(driver, 500).until(EC.element_to_be_clickable((By.NAME, "password")))
    driver.find_element_by_name('password').send_keys(password)
    driver.find_element_by_class_name('CwaK9').click()
    WebDriverWait(driver, 500).until(EC.element_to_be_clickable((By.ID, "identity-prompt-confirm-button")))
    driver.find_element_by_id('identity-prompt-confirm-button').click()

    #driver.get('https://www.youtube.com/watch?v=FFDDN1C1MEQ')  # If I do a simple direct link like here, it works

    urls = []

    # You can add in a file and import from there

    inp = open ("urls.txt","r")
    for line in inp.readlines():
        urls.append(line.split())

    for url in urls:        
        driver.get(url)

youtube_login()

1 个答案:

答案 0 :(得分:1)

我认为您的urls.txt网址格式不正确

尝试像这样调试URL:

from selenium.common.exceptions import InvalidArgumentException

for url in urls:
    try:        
       driver.get(url)
    except InvalidArgumentException:
       print(url)