昨天昨天一切正常,但是今天我收到了这个错误:
我试图通过类名xpath查找元素,但是这些都不起作用。追踪(最近一次通话):文件“ bot.py”,第31行,在ig_bot = InstagramBot('temp_username','temp_password')文件“ bot.py”,第13行,位于[[initself.login()文件“ bot.py”,第20行,登录self.driver.find_element_name('username')。send_keys(self.username)selenium.common.exceptions.NoSuchElementException:消息:没有这样的消息元素:无法找到元素:{“ method”:“ css选择器”,“选择器”:“。username”}(会话信息:chrome = 77.0.3865.90)
bot.py
from selenium import webdriver
import os
import time
class InstagramBot:
def __init__(self, username, password):
self.username = username
self.password = password
self.driver = webdriver.Chrome('chromedriver.exe')
self.base_url = 'https://www.instagram.com'
self.login()
def login(self):
self.driver.get('{}/accounts/login/?source=auth_switcher'.format(self.base_url))
time.sleep(2)
self.driver.find_element_by_name('username').send_keys(self.username)
self.driver.find_element_by_name('password').send_keys(self.password)
time.sleep(1)
self.driver.find_elements_by_xpath("//div[contains(text(), 'Log In')]")[0].click()
def nav_user(self, user):
self.driver.get('{}/{}/'.format(self.base_url, user))
if __name__ == '__main__':
ig_bot = InstagramBot('temp_username', 'temp_password')
ig_bot.nav_user('garyvee')
html
<input class="_2hvTZ pexuQ zyHYP" aria-label="Phone number, username, or email" aria-required="true" autocapitalize="off" autocorrect="off" maxlength="75" name="username" type="text" value="">
find_element_by_name
而不是find_element_by_class_name
。Chrome控制台的输出:
document.getElementsByName("username")[0];
<input class="_2hvTZ pexuQ zyHYP" aria-label="Phone number, username, or email" aria-required="true" autocapitalize="off" autocorrect="off" maxlength="75" name="username" type="text" value autocomplete="off" style="background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAkCAYAAADo6zjiAAAAAXNSR0IArs4c6QAAAnVJREFUWAntVzuL4lAUPokBsVB0t9odK8VCLCal3Q4WbmUpCFv6DyymEmys9gf4B4RlS7GwEWQsBAsL195q2J3KWIiVrz0nJBcTk9yr3jCw7AG5j3PO9325j2OiAFq73X7Y7/ffsft0Op0+05wsUxTlD2K9aJr23Gw2f7txFYv8FxJ/dDtljlHICkU8ukWo9ORhk9ODEIe1yo7nUnH05JgJd3DBpcre8yD9Xly0Au9q/7aAfD4PjUYDqPWzUFegUChAIpEAav0sVAF4901eu/USEaoAL0L3nENANBqFbDYLqVTKHQe3+i6AXBOaPU4mk1Cv1yEej8PxeIR+vw/z+dx03+qzsYNatgLFYtEkp2BVVaFUKrG8W30MIKDDBATEhOpiAqbTKWw2G5OMtmA0GjHiW30MIKCjtFqtk+2ng5ZOp8EwDFiv1/a02Qb5HIGcAV7JNwwZW+8Hrw4BnFypbhRioAidbYFUdAEw/Gf8QO8H7ybA0viF1QEB0cIhmUwGqtUqxGIxM2cymcBwOLzIx1X4JF0A1YxyuWzWkgtGjwlpAiKRCFQqFdB13YPGf0qagFqtBrlczmSiOkJGFZVnKl4Hem+/26hYEfHhcIBerwe73U4IkyS+CEVygpbLJQwGA+h2u7BYLIC2RMSwFmjPeB+/4om8+8NkNpsxzqCXEBaEHZW+VFDEIyb8kLUd5wS8vnkIrc+lb7xg8p//d4jE82L4x5SHcKf/v4CrCxEe1Deq4byVX61WrBBtt1vPcMK6WgAijfFX80Q8m+x0Omcj3+746jNAdQOVG76Qgg7CIKyrBeCVfcVEHQF+0hIK8rEwyqFcwiCsv+R847qxq2vXAAAAAElFTkSuQmCC"); background-repeat: no-repeat; background-attachment: scroll; background-size: 16px 18px; background-position: 98% 50%;">