#!/usr/bin/env python
# -*- coding: utf-8 -*-
# based on: https://stackoverflow.com/questions/74793705/how-to-load-chrome-options-using-undetected-chrome
# uses CDP to override the user agent header
import time,os,sys
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import json, base64
def send_command_return_result(driver, cmd, params = {}, resultkey = 'windowId'):
post_url = driver.command_executor._url + '/session/{0:s}/chromium/send_command_and_get_result'.format( driver.session_id)
response = driver.command_executor._request('POST', post_url, json.dumps({'cmd': cmd, 'params': params}))
print('response: {}'.format(response))
if ('status' in response ) and response['status']:
raise Exception(response.get('value'))
return response.get('value').get(resultkey)
def send_command(driver, cmd, params = {}):
post_url = driver.command_executor._url + '/session/{0:s}/chromium/send_command_and_get_result'.format( driver.session_id)
response = driver.command_executor._request('POST', post_url, json.dumps({'cmd': cmd, 'params': params}))
if ('status' in response ) and response['status']:
raise Exception(response.get('value'))
global debug
debug = False
if __name__ == '__main__':
webdriver_options = Options()
# comment to see the browser window
webdriver_options.add_argument('--headless')
webdriver_options.add_argument('--disable-gpu')
# for annotated list of chrome headless flags, see
# https://peter.sh/experiments/chromium-command-line-switches/
# https://groups.google.com/forum/#!topic/selenium-users/SnxpvG8Erj4
if os.getenv('OS') != None :
homedir = os.getenv('USERPROFILE').replace('\\', '/')
is_windows = True
else:
homedir = os.getenv('HOME')
is_windows = False
chromedriver_path = homedir + os.sep + 'Downloads' + os.sep + ('chromedriver.exe' if is_windows else 'chromedriver')
driver = webdriver.Chrome(chromedriver_path, options = webdriver_options)
# https://chromedevtools.github.io/devtools-protocol/tot/Network/#method-setUserAgentOverride
send_command(driver,
'Network.setUserAgentOverride', {
'userAgent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:72.0) Gecko/20100101 Firefox/72.0',
}
)
url = 'https://www.whatismybrowser.com/detect/what-http-headers-is-my-browser-sending'
driver.get(url)
time.sleep(5)
xpath = '//*[@id="content-base"]//table//th[contains(text(),"USER-AGENT")]/../td'
element = driver.find_element_by_xpath(xpath)
print( element.get_attribute('innerHTML'))
driver.quit()
# PATH=%PATH%;c:\Python381;%USERPROFILE%\Downloads
self.options.add_experimental_option('excludeSwitches', ['disable-popup-blocking'])
driver.find_element(By.CSS_SELECTOR, ".calendar__day-cell")
@
перед именем атрибута в []
driver.find_element(By.CSS_SELECTOR, "div[aria-label='Sat Dec 17 2022']")
wait.Until(x => {
var size =
x.FindElement(By.CssSelector(selector)).GetAttribute("value").Length;
if (size >= 5) {
return true;
} else {
Console.Error.Write("waiting for specific text length");
return false;
}
});
homedir = getenv('HOME')
options.add_argument('--user-data-dir="{}"'.format(homedir))
options.add_argument('--remote-debugging-port=9222')
HOME
, подправьте screenshot_as_png
writer = csv.writer(csvfile, delimiter=' ', quotechar='|', quoting=csv.QUOTE_MINIMAL)
writer.writerow([name_of_restauran.texе])
delimiter
options.add_argument("user-agent=Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.107 Safari/537.36")
text = 'Continue to Discord'
text = 'Принять приглашение'
driver.find_element_by_xpath('//button/div[contains(text(), "{}")]'.format(text))
{"method":"xpath","selector":"//button/div[contains(text(), "Принять приглашение")]"}
from cyrtranslit import to_latin
from selenium import webdriver
from selenium.webdriver.firefox.webdriver import WebDriver
def waittest:
def __init__(self, selector, value):
self.selector = selector
self.value = value
def __call__(self, driver):
element = driver.find_element_by_css_selector(self.selector)
text = element.text
print('checking text: "{}" against "{}"'.format(to_latin(text, 'ru'), self.value))
if to_latin(text, 'ru') == self.value:
return element
else:
return None
text = to_latin('Принять приглашение', 'ru')
element = WebDriverWait(driver, 10).until( waittest("button[class *= 'button']", text))
element = driver.execute_script("return document.querySelector('form table tr:first-child td:nth-child(2) b')")
value = element.text
url = 'https://www.youtube.com/'
title = 'YouTube'
driver = webdriver.Chrome()
driver.get(url)
try:
# https://selenium-python.readthedocs.io/waits.html
WebDriverWait(driver,10).until(EC.title_contains(title))
except (NoAlertPresentException, TimeoutException) as e:
print('page was not shown: {0}'.format(e))
finally:
driver.quit()