首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用selenium和phantomJS更改"user-agent“标头

使用selenium和phantomJS更改"user-agent“标头
EN

Stack Overflow用户
提问于 2015-09-22 04:27:20
回答 1查看 3K关注 0票数 3

我试图使用selenium登录到一个表单,但得到了一个奇怪的错误。我确信这与user-agent头有关,但如果不是这样,我想知道怎么做。

下面是记录在表单中的函数:

代码语言:javascript
复制
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)

下面是我运行该函数时得到的结果:

代码语言:javascript
复制
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数据中,我注意到

代码语言:javascript
复制
{"User-agent":"Python-urllib/3.5}

因此,我尝试更改标头的尝试没有成功。我是否正确使用了所需的功能?我还漏掉了什么?我是个网络抓取新手,所以它真的可以是任何东西。

耽误您时间,实在对不起

EN

回答 1

Stack Overflow用户

发布于 2015-09-22 04:38:58

另一个具有id="username"的隐藏字段在这里造成了问题。

理想情况下,您应该使定位器更具体,以匹配可见元素,例如:

代码语言:javascript
复制
driver.find_element_by_css_selector("div.login-form #username")

您还可以通过以下方式过滤出可见元素:

代码语言:javascript
复制
username = next(element for element in driver.find_elements_by_id("username") 
                if element.is_displayed())
username.send_keys("test")

在搜索元素之前,您可能还需要添加一个显式等待:

代码语言:javascript
复制
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"))
)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32703995

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档