0

我有这个代码:

#!/usr/bin/env python
from pyvirtualdisplay import Display
from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from selenium.webdriver.support.ui import Select
from pyquery import *
# declaration of variables
display = Display(visible=0, size=(800, 600))
display.start()
firefox_capabilities = DesiredCapabilities.FIREFOX
firefox_capabilities['marionette'] = True
# Initialize
driver = webdriver.Firefox(capabilities=firefox_capabilities)
driver.maximize_window()
driver.implicitly_wait(10)
driver.get('https://sjobs.brassring.com/TGWebHost/searchopenings.aspx?partnerid=25222&siteid=5011')
print driver.title
# below does not work
# driver.find_element_by_xpath(".//*[@id='Question4138__FORMTEXT62']/option[37]").click()
# selectsoptions = driver.find_element_by_id("Question4138__FORMTEXT62")
# for option in selectsoptions .find_elements_by_tag_name('option'):
  # if option.text == 'Calgary':
    # option.select()
    # break
driver.find_element_by_id('ctl00_MainContent_submit1').click()
# call a sub-routine function def (not shown here)
save_rows(driver.find_element_by_id('idSearchresults'))
driver.close()
display.stop()

输出:

“搜索工作 - 沃尔玛加拿大职业”

问题是我不知道如何在“加拿大城市”字段中选择“卡尔加里”。我尝试了许多不同的方法,但仍然不起作用。你能帮忙吗?

注意:我可以选择选项,并且我的代码在非无头环境 Windows 机器中工作,这里是python selenium-webdriver 选择选项不起作用。我现在正在处理生产无头 Ubuntu,因此浏览器并没有在任何物理显示器上真正打开。

再次提前感谢。

4

2 回答 2

0

在这里,我会给你代码。请检查一下。

# -*- coding: utf-8 -*-

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time

driver = webdriver.Chrome("chromedriver.exe")
driver.get("https://sjobs.brassring.com/TGWebHost/searchopenings.aspx?partnerid=25222&siteid=5011")
ele = driver.find_element_by_xpath("//option[contains(text(),'Calgary  ')]")
print ele
driver.execute_script("arguments[0].scrollIntoView()",ele)
time.sleep(2)
ele.click()
于 2016-10-26T06:57:24.050 回答
0

测试解决方案:

答案是使用 PhantomJS 无头 Webkit 浏览器,它可以在 Window 和 Linux 上使用完全相同的代码。这是示例:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select
from pyquery import *
import json
import csv
import sys
import time

def save_rows(elements):
    rows = elements.find_element_by_id('idSearchresults_dataBody')
    for row in rows.find_elements_by_tag_name('tr'):
        link = row.find_element_by_css_selector('a').get_attribute('href')
        print link

driver = webdriver.PhantomJS(service_args=['--ssl-protocol=any'])
driver.implicitly_wait(10)
driver.get('https://sjobs.brassring.com/TGWebHost/searchopenings.aspx?partnerid=25222&siteid=5011')

text = "Calgary"
currentselection = driver.find_element_by_id("Question4138__FORMTEXT62")
select = Select(currentselection)
select.deselect_by_visible_text("All")
select.select_by_visible_text(text)

driver.find_element_by_id('ctl00_MainContent_submit1').click()

save_rows(driver.find_element_by_id('idSearchresults'))

driver.quit()
于 2016-10-28T16:39:21.647 回答