簡體   English   中英

使用selenium和phantomJS更改“user-agent”標頭

[英]Changing the “user-agent” header using selenium with phantomJS

我正在嘗試使用selenium登錄表單,並得到一個奇怪的錯誤。 我很肯定它與用戶代理標題有關,但如果沒有,我想知道如何做到這一點。

這是登錄表單的功能:

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}

所以我嘗試更改標題是不成功的。 我使用所需的功能嗎? 我還缺少什么? 我是網絡抓取的新手,所以它真的可以是任何東西。

謝謝你的時間

具有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"))
)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM