本文整理汇总了Python中selenium.webdriver.Chrome方法的典型用法代码示例。如果您正苦于以下问题:Python webdriver.Chrome方法的具体用法?Python webdriver.Chrome怎么用?Python webdriver.Chrome使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类selenium.webdriver
的用法示例。
在下文中一共展示了webdriver.Chrome方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: process_request
# 需要导入模块: from selenium import webdriver [as 别名]
# 或者: from selenium.webdriver import Chrome [as 别名]
def process_request(self, request):
"""使用selenium模拟点击,获取js等操作,所以需要重写process_request方法"""
# 获取调度器返回的url
url = request.url
if 'month=' in url:
# 手动打开chrome发送请求,执行js
driver = webdriver.Chrome()
driver.get(url=url)
# 延迟一下,让页面进行加载
time.sleep(4)
data = driver.page_source.encode()
driver.close()
# 返回数据给引擎
resp = HtmlResponse(
url=url,
body=data,
request=request,
encoding='utf8'
)
return resp
示例2: login
# 需要导入模块: from selenium import webdriver [as 别名]
# 或者: from selenium.webdriver import Chrome [as 别名]
def login(name, passwd):
url = 'https://passport.baidu.com/v2/?login'
# 这里可以用Chrome、Phantomjs等,如果没有加入环境变量,需要指定具体的位置
driver = webdriver.Chrome()
driver.get(url)
print('开始登录')
name_field = driver.find_element_by_id('TANGRAM__PSP_3__userName')
name_field.send_keys(name)
time.sleep(1)
passwd_field = driver.find_element_by_id('TANGRAM__PSP_3__password')
passwd_field.send_keys(passwd)
time.sleep(1)
login_button = driver.find_element_by_id('TANGRAM__PSP_3__submit')
login_button.click()
time.sleep(5)
driver.quit()
#return driver.get_cookie("BDUSS")
return driver.get_cookies()
示例3: generate_threaded_streaming
# 需要导入模块: from selenium import webdriver [as 别名]
# 或者: from selenium.webdriver import Chrome [as 别名]
def generate_threaded_streaming(obj: stream.Streaming, stream_name, dir, duration, chrome_options=None, num_threads=5):
#### STREAMING ####
# Create filename
now = datetime.datetime.now()
file = dir + "/%s-%.2d%.2d_%.2d%.2d%.2d.pcap" % (stream_name, now.day, now.month, now.hour, now.minute, now.second)
# Instantiate thread
capture_thread = Thread(target=cap.captureTraffic, args=(1, duration, dir, file))
# Create five threads for streaming
streaming_threads = []
browsers = []
for i in range(num_threads):
browser = webdriver.Chrome(options=chrome_options)
browser.implicitly_wait(10)
browsers.append(browser)
t = Thread(target=obj.stream_video, args=(obj, browser))
streaming_threads.append(t)
return browsers, capture_thread, file, streaming_threads
示例4: _add_chrome_options
# 需要导入模块: from selenium import webdriver [as 别名]
# 或者: from selenium.webdriver import Chrome [as 别名]
def _add_chrome_options(self, options, option_name):
"""Add Chrome options from properties file
:param options: chrome options object
:param option_name: chrome option name
"""
options_conf = {'prefs': {'section': 'ChromePreferences', 'message': 'preference'},
'mobileEmulation': {'section': 'ChromeMobileEmulation', 'message': 'mobile emulation option'}}
option_value = dict()
try:
for key, value in dict(self.config.items(options_conf[option_name]['section'])).items():
self.logger.debug("Added chrome %s: %s = %s", options_conf[option_name]['message'], key, value)
option_value[key] = self._convert_property_type(value)
if len(option_value) > 0:
options.add_experimental_option(option_name, option_value)
except NoSectionError:
pass
示例5: __init__
# 需要导入模块: from selenium import webdriver [as 别名]
# 或者: from selenium.webdriver import Chrome [as 别名]
def __init__(self):
self.web=webdriver.Chrome()
self.web.get('https://user.qzone.qq.com')
config = configparser.ConfigParser(allow_no_value=False)
config.read('userinfo.ini')
self.__username =config.get('qq_info','qq_number')
self.__password=config.get('qq_info','qq_password')
self.headers={
'host': 'h5.qzone.qq.com',
'accept-encoding':'gzip, deflate, br',
'accept-language':'zh-CN,zh;q=0.8',
'accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
'user-agent':'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36',
'connection': 'keep-alive'
}
self.req=requests.Session()
self.cookies={}
示例6: __init__
# 需要导入模块: from selenium import webdriver [as 别名]
# 或者: from selenium.webdriver import Chrome [as 别名]
def __init__(self):
super(HeadlessChromeLocust, self).__init__()
options = webdriver.ChromeOptions()
options.add_argument('headless')
options.add_argument('window-size={}x{}'.format(
self.screen_width, self.screen_height
))
options.add_argument('disable-gpu')
if self.proxy_server:
_LOGGER.info('Using proxy: ' + self.proxy_server)
options.add_argument('proxy-server={}'.format(self.proxy_server))
driver = webdriver.Chrome(chrome_options=options)
_LOGGER.info('Actually trying to run headless Chrome')
self.client = RealBrowserClient(
driver,
self.timeout,
self.screen_width,
self.screen_height,
set_window=False
)
示例7: get_cookie_by_selenium
# 需要导入模块: from selenium import webdriver [as 别名]
# 或者: from selenium.webdriver import Chrome [as 别名]
def get_cookie_by_selenium(username, password): # 获取Cookies
url = 'https://passport.baidu.com/v2/?login'
# 如果没有加入环境变量,需要指定具体的位置
# driver = webdriver.Chrome(executable_path='/Users/resolvewang/Documents/program/driver/chromedriver')
driver = webdriver.Chrome()
driver.get(url)
log.info('开始登录')
name_field = driver.find_element_by_id('TANGRAM__PSP_3__userName')
name_field.send_keys(username)
time.sleep(1)
passwd_field = driver.find_element_by_id('TANGRAM__PSP_3__password')
passwd_field.send_keys(password)
time.sleep(1)
login_button = driver.find_element_by_id('TANGRAM__PSP_3__submit')
login_button.click()
time.sleep(5)
#return driver.get_cookie("BDUSS")
login_cookie = ''
for cookie in driver.get_cookies():
login_cookie += cookie['name'] + '=' + cookie['value'] + ';'
driver.quit()
return login_cookie if try_cookie_logined(login_cookie) else log.warning("登陆失败")
示例8: __init__
# 需要导入模块: from selenium import webdriver [as 别名]
# 或者: from selenium.webdriver import Chrome [as 别名]
def __init__(self, use_Dingtalk=False):
chrome_options = Options()
self.__exit_flag = threading.Event()
self.__exit_flag.clear()
self.use_Dingtalk = use_Dingtalk
if config['mute']:
chrome_options.add_argument('--mute-audio') # 关闭声音
if os.path.exists('driver/chrome.exe'):
chrome_options.binary_location = 'driver/chrome.exe'
# chrome_options.add_argument('--no-sandbox')#解决DevToolsActivePort文件不存在的报错
# chrome_options.add_argument('window-size=800x600') #指定浏览器分辨率
# chrome_options.add_argument('--disable-gpu') #谷歌文档提到需要加上这个属性来规避bug
# chrome_options.add_argument('--hide-scrollbars') #隐藏滚动条, 应对一些特殊页面
# chrome_options.add_argument('blink-settings=imagesEnabled=false') #不加载图片, 提升速度
if config['background_process'] and self.use_Dingtalk:
chrome_options.add_argument('--headless') # 浏览器不提供可视化页面. linux下如果系统不支持可视化不加这条会启动失败
self.driver = webdriver.Chrome('driver/chromedriver.exe', options=chrome_options)
LOGGER.setLevel(logging.CRITICAL)
示例9: __init__
# 需要导入模块: from selenium import webdriver [as 别名]
# 或者: from selenium.webdriver import Chrome [as 别名]
def __init__(self):
self.browse = None
self.source_playlist = None
self.target_playlist_tag = None
self.success_list = list()
self.failed_list = list()
os.environ["webdriver.chrome.driver"] = chrome_driver_path
os.environ["webdriver.phantomjs.driver"] = phantomjs_driver_path
# chromedriver = chrome_driver_path
phantomjs_driver = phantomjs_driver_path
opts = Options()
opts.add_argument("user-agent={}".format(headers["User-Agent"]))
# browser = webdriver.Chrome(chromedriver)
browser = webdriver.PhantomJS(phantomjs_driver)
self.browser = browser
self.wait = ui.WebDriverWait(self.browser, 5)
self.config = Config()
示例10: driver
# 需要导入模块: from selenium import webdriver [as 别名]
# 或者: from selenium.webdriver import Chrome [as 别名]
def driver():
options = Options()
options.headless = True
arguments = ['--incognito', '--private']
if platform.system() == 'Darwin':
chrome_path = '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'
data_dir = os.path.join(tempfile.gettempdir(), 'local-probe-chrome-data')
options.binary_location = chrome_path
else:
arguments.extend(['--no-sandbox', '--disable-dev-shm-usage'])
data_dir = '/home/circleci/project/data'
arguments.append('--user-data-dir={}'.format(data_dir))
for argument in arguments:
options.add_argument(argument)
result = webdriver.Chrome(options=options)
result.set_window_size(1600, 1000)
yield result
result.close()
示例11: _driver
# 需要导入模块: from selenium import webdriver [as 别名]
# 或者: from selenium.webdriver import Chrome [as 别名]
def _driver():
options = Options()
options.headless = True
arguments = ['--incognito', '--private']
chrome_path = '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'
data_dir = os.path.join(tempfile.gettempdir(), 'local-probe-chrome-data')
options.binary_location = chrome_path
arguments.append('--user-data-dir={}'.format(data_dir))
for argument in arguments:
options.add_argument(argument)
result = webdriver.Chrome(options=options)
try:
result.set_window_size(1600, 1000)
yield result
finally:
result.close()
示例12: test_chrome_manager_cached_driver_with_selenium
# 需要导入模块: from selenium import webdriver [as 别名]
# 或者: from selenium.webdriver import Chrome [as 别名]
def test_chrome_manager_cached_driver_with_selenium():
custom_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), "custom")
manager = ChromeDriverManager(path=custom_path)
driver = webdriver.Chrome(manager.install())
driver.get("http://automation-remarks.com")
metadata_file = os.path.join(custom_path, 'drivers.json')
with open(metadata_file) as json_file:
data = json.load(json_file)
for k in data.keys():
data[k]['timestamp'] = "08/06/2019"
with open(metadata_file, 'w') as outfile:
json.dump(data, outfile)
ChromeDriverManager(path=custom_path).install()
示例13: start_session
# 需要导入模块: from selenium import webdriver [as 别名]
# 或者: from selenium.webdriver import Chrome [as 别名]
def start_session(username, password):
print("Opening Browser...")
wd_options = Options()
wd_options.add_argument("--disable-notifications")
wd_options.add_argument("--disable-infobars")
wd_options.add_argument("--mute-audio")
wd_options.add_argument("--start-maximized")
driver = webdriver.Chrome(chrome_options=wd_options)
#Login
driver.get("https://www.facebook.com/")
print("Logging In...")
email_id = driver.find_element_by_id("email")
pass_id = driver.find_element_by_id("pass")
email_id.send_keys(username)
pass_id.send_keys(password)
driver.find_element_by_id("loginbutton").click()
return driver
示例14: driver
# 需要导入模块: from selenium import webdriver [as 别名]
# 或者: from selenium.webdriver import Chrome [as 别名]
def driver():
options = webdriver.ChromeOptions()
options.add_argument("disable-gpu")
options.add_argument("headless")
options.add_argument("no-default-browser-check")
options.add_argument("no-first-run")
options.add_argument("no-sandbox")
d = DesiredCapabilities.CHROME
d["loggingPrefs"] = {"browser": "ALL"}
driver = webdriver.Chrome(options=options, desired_capabilities=d)
driver.implicitly_wait(30)
yield driver
driver.quit()
示例15: getWebDriver
# 需要导入模块: from selenium import webdriver [as 别名]
# 或者: from selenium.webdriver import Chrome [as 别名]
def getWebDriver():
if not os.path.isfile(cfg['WEBDRIVER']['PATH']):
print("{0} does not exist - install a webdriver".format(cfg['WEBDRIVER']['PATH']))
sys.exit(-2)
d = cfg['WEBDRIVER']['ENGINE']
if d.lower() == 'firefox':
os.environ["webdriver.firefox.driver"] = cfg['WEBDRIVER']['PATH']
p = os.path.join(tempfile.gettempdir(), 'imageraider')
if not os.path.isdir(p):
os.makedirs(p)
profile = webdriver.FirefoxProfile()
profile.set_preference('browser.download.folderList', 2) # custom location
profile.set_preference('browser.download.manager.showWhenStarting', False)
profile.set_preference('browser.download.dir', p)
profile.set_preference('browser.helperApps.neverAsk.saveToDisk', 'text/csv')
profile.set_preference("browser.link.open_newwindow", 3)
profile.set_preference("browser.link.open_newwindow.restriction", 2)
return webdriver.Firefox(profile)
else:
os.environ["webdriver.chrome.driver"] = cfg['WEBDRIVER']['PATH']
return webdriver.Chrome()