我正在尝试使用 selenium 登录表单,但出现了一个奇怪的错误。我肯定它与用户代理 header 有关,但如果不是,我想知道如何做。
这是在表单中记录的函数:
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}
所以我更改 header 的尝试没有成功。我是否使用了所需的功能?还有什么我想念的吗?我是网络抓取的新手,所以它真的可以是任何东西。
谢谢你的时间
最佳答案
另一个具有 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"))
)
关于python - 使用 selenium 和 phantomJS 更改 "user-agent" header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32703995/