python - 使用 selenium 和 phantomJS 更改 "user-agent" header

标签 python selenium selenium-webdriver phantomjs

我正在尝试使用 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/

相关文章:

java - org.openqa.selenium.StaleElementReferenceException : stale element reference: element is not attached to the page document

python setup.py install 更改脚本解释器

python - 属性错误: Object has no attribute 'listbox

java - 如何在 selendroid 中验证 toast 消息

java - 无法使用 selenium java 选择单选按钮

java - TestNG 中的非静态驱动程序和屏幕截图监听器

python - Pandas:使用时间序列作为选择的掩码

python - 解析 json 数据时仅检索前 2 个值

selenium - 如何使用 Selenium Java WebDriver 选择复选框?

javascript - 如何读取元素值和点击时间量