Я использую привязки selenium-python, чтобы выполнить некоторые базовые проверки браузера. Мне нужно щелкнуть элемент, который по умолчанию невидим. Я проверил его на is_displayed() method
. Итак, я попытался использовать метод execute_script
, чтобы сделать его видимым с помощью следующего кода, но я получаю сообщения об ошибках. Его общий сценарий, когда нам нужно сделать невидимый элемент видимым. Должны быть и другие способы обойти подобные проблемы. Будет полезно, если кто-нибудь укажет мне на проблему в моем коде. Можно ли щелкнуть элемент с чистым js внутри кода python?Selenium-python делает невидимый элемент видимым
print "getting keyword ideas"
searches = driver.find_element_by_xpath("//*[contains(text(), 'Avg. monthly searches')]")
driver.execute_script("arguments.style.visibility='visible';", searches)
и сообщение об ошибке:
Traceback (самый последний вызов последнего): Файл "C: \ виртуальных доменов \ phpsols \ осколок \ adwords.py", строка 140, в водителя. execute_script ("arguments.style.visibility = 'visible';", search) Файл "C: \ anaconda32 \ lib \ site-packages \ selenium \ webdriver \ remote \ webdriver.py", строка 429, в файле execute_script { 'script': script, 'args': convert_args}) ['value'] Файл "C: \ anaconda32 \ lib \ site-packages \ selenium \ webd river \ remote \ webdriver.py ", строка 201, в исполнении self.error_handler.check_response (response) Файл" C: \ anaconda32 \ lib \ site-packages \ selenium \ webdriver \ remote \ errorhandler.py ", строка 181, в check_response raise exception_class (message, screen, stacktrace) selenium.common.exceptions.WebDriverException: Message: {"errorMessage": "undefined не является объектом (оценка " arguments.style.visibility = 'visible' «) " "запрос": { "заголовки": { "Accept": "приложения/JSON", "Accept-Encoding": "идентичность", "соединение": "закрыть", "Content-Length":" 210 », "Content-Type": "приложения/JSON; кодировка = UTF-8", "хост": "127.0.0.1:55867","User-Agent":"Python-urllib/2.7"},"httpVersion" : «1.1», «метод»: «POST», «post»: «{\" sessionId \ ": \" 8f05e120-f672-11e5-91c5-c7097c43ddb4 \ " , \ "args \": [{\ "element-6066-11e4-a52e-4f735466cecf \": \ ": wdc: 1459340795815 \", \ "ELEMENT \": \ ": wdc: 1459340795815 \"}] , \ "script \": \ "arguments.style.visibility = 'visible'; \"} "," url ":"/execute "," urlParsed ": {" anchor ":" "," query ": "", "файл": "выполнить", "каталог": "/", "путь": "/ выполнить", "относительный": "/ выполнить", "порт": "", "хозяин": "" , "пароль": "", "пользователь": "", "USERINFO": "", "власть": "", "протокол": "", "источник": "/ выполнить", "queryKey": { }, "куски": [ "выполнить"]}, "urlOriginal": "/ сеанса/8f05e120-f672-11e5-91c5-c7097c43ddb4/выполнить"}} Снимок экрана: доступны через экран
<div id="gwt-debug-column-SEARCH_VOLUME_PRIMARY-header-0-0">
<div style="text-align:right">Avg. monthly searches
<span class="table-tooltip" id="gwt-debug-tooltip-4580983"> </span>
<br>
</div>
</div>
Вот код python:
print "getting keyword ideas"
driver.execute_script('document.getElementById("gwt-debug-column-SEARCH_VOLUME_PRIMARY-header-0-0").style.visibility = "visible";')
driver.execute_script('document.getElementById("gwt-debug-column-SEARCH_VOLUME_PRIMARY-header-0-0").style.display = "block";')
searches = driver.find_element_by_xpath("//*[contains(text(), 'Avg. monthly searches')]")
if searches.is_displayed():
print "searches is visible"
else:
print "searches isn't visible"
avg_monthly_searches = driver.find_elements_by_id("gwt-debug-column-SEARCH_VOLUME_PRIMARY-header-0-0")
for avg in avg_monthly_searches:
if avg.is_displayed():
print "element is visible, so clicking ..."
actions = ActionChains(driver)
actions.click(on_element=avg).perform()
time.sleep(10)
print "scrolling to the bottom"
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
print "getting the page source as interpreted by chromedriver"
driver.execute_script('return document.documentElement.innerHTML')
print "getting keyword ideas source"
content = driver.page_source
with open('keyword_ideas.html', 'w') as f:
f.write(content.encode('utf-8'))
time.sleep(5)
print "getting html"
dom = DOM(content)
print "traversing ... "
for e in dom('td.spgb-f'):
for a in e('a.sptc-e.sptc-h'):
print repr(plaintext(a.content))
else:
print "element isn't visible"
обеспечивает 'HTML' образец кода для невидимого элемента – Andersson
@Andersson, я добавил HTML части –
Вы уверены, что вы хотите нажать' div' элемент? Это действительно интерактивно? – Andersson