我试图使用selenium登录到一个表单,但得到了一个奇怪的错误。我确信这与user-agent头有关,但如果不是这样,我想知道怎么做。
下面是记录在表单中的函数:
def log_in_phantom(username, password, url):
dcap = dict(DesiredCapabilities.PHANTOMJS)
dcap["phantomjs.page.settings.userAgent"] = (<My user-agent>)
browser = webdriver.PhantomJS(desired_capabilities = dcap)
browser.get(url)
browser.implicitly_wait(3)
username = browser.find_element_by_id("username")
if username.is_displayed():
username.send_keys(username)
password = browser.find_element_by_id("password")
if password.is_displayed():
password.send_keys(password)
button = browser.find_element_by_class_name("btn-default")
if button.is_displayed:
button.click()
session = browser.session_id
print(browser.current_url)下面是我运行该函数时得到的结果:
selenium.common.exceptions.ElementNotVisibleException: Message: Error Message => 'Element is not currently visible and may not be manipulated'
caused by Request => {<bunch of cookie data>}在这个cookie数据中,我注意到
{"User-agent":"Python-urllib/3.5}因此,我尝试更改标头的尝试没有成功。我是否正确使用了所需的功能?我还漏掉了什么?我是个网络抓取新手,所以它真的可以是任何东西。
耽误您时间,实在对不起
发布于 2015-09-22 04:38:58
另一个具有id="username"的隐藏字段在这里造成了问题。
理想情况下,您应该使定位器更具体,以匹配可见元素,例如:
driver.find_element_by_css_selector("div.login-form #username")您还可以通过以下方式过滤出可见元素:
username = next(element for element in driver.find_elements_by_id("username")
if element.is_displayed())
username.send_keys("test")在搜索元素之前,您可能还需要添加一个显式等待:
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.ID, "username"))
)https://stackoverflow.com/questions/32703995
复制相似问题