Получить URL из атрибута onclick тега python - PullRequest
2 голосов
/ 18 октября 2019

Я пытаюсь получить доступ к URL-адресу, присутствующему в атрибуте onclick тега, используя python для селена. Он присутствует в функции JavaScript. Я пробовал разные методы для этого, но пока не нашел решения. Я попытался выполнить функцию по нажатию, используя метод execute_script. Я также пробовал get_attribute, чтобы получить функцию onclick, но она ничего не возвращает. Я хочу получить доступ к URL-адресу, присутствующему в функции openPopUpFullScreen

Вот HTML-код:

<td class="tdAction">
<div class="formResponseBtn icon-only">
<a href="#fh" onclick="javascript: openPopUpFullScreen('/esop/toolkit/negotiation/rfq/publicRfqSummaryReport.do?rfqId=rfq_229969', '');" class="openNewPage" title="Open a new window to view > View or download a Summary of this PQQ/ITT which includes details of the PQQ/ITT settings, format and questions">
<img src="/esop_custom/images/buttons/print_button.png" title="Open a new window to view > View or download a Summary of this PQQ/ITT which includes details of the PQQ/ITT settings, format and questions" alt="Open a new window to view > View or download a Summary of this PQQ/ITT which includes details of the PQQ/ITT settings, format and questions"><img src="/esop_custom/images/buttons/openNewWindow_button.png" title="(Opens in new window)" alt="(Opens in new window)">
</a>
</div>
</td>

Вот код Python:

url=browser.find_element_by_xpath("//img[@title='Open a new window to view > View or download a Summary of this PQQ/ITT which includes details of the PQQ/ITT settings, format and questions']").click()
print(browser.current_url)
#it returns the previous page I am at.

Вот еще один:

id=browser.find_element_by_css_selector(".openNewPage").get_attribute("onclick")
print(id)
#it returns none

Мне нужен URL-адрес, присутствующий в функции openPopUpFullScreen, но я не могу выяснить, каким будет правильное решение, чтобы сделать это.

Обновление: я также пытался использовать beautifulsoup для извлеченияфункция onclick, но она не отображается:

Вот мой код:

content = browser.page_source.encode('utf-8').strip()
soup = BeautifulSoup(content,"html.parser")
res = soup.find("a",{"class":"openNewPage"})
print(res)
#it returns the complete tag but it does not contain onclick attribute
#i tried using this
res = soup.find("a",{"class":"openNewPage"})[onclick]
#it returns an error NameError: name 'onclick' is not defined

Ответы [ 2 ]

1 голос
/ 18 октября 2019

Ниже

from bs4 import BeautifulSoup


html = '''<td class="tdAction">
<div class="formResponseBtn icon-only">
<a href="#fh" onclick="javascript: openPopUpFullScreen('/esop/toolkit/negotiation/rfq/publicRfqSummaryReport.do?rfqId=rfq_229969', '');" class="openNewPage" title="Open a new window to view > View or download a Summary of this PQQ/ITT which includes details of the PQQ/ITT settings, format and questions">
<img src="/esop_custom/images/buttons/print_button.png" title="Open a new window to view > View or download a Summary of this PQQ/ITT which includes details of the PQQ/ITT settings, format and questions" alt="Open a new window to view > View or download a Summary of this PQQ/ITT which includes details of the PQQ/ITT settings, format and questions"><img src="/esop_custom/images/buttons/openNewWindow_button.png" title="(Opens in new window)" alt="(Opens in new window)">
</a>
</div>
</td>'''


soup = BeautifulSoup(html, features="lxml")
a = soup.find('a')
onclick = a.attrs['onclick']
left = onclick.find("'")
right = onclick.find("'",left+1)
print('URL is: {}'.format(onclick[left+1:right]))

выход

URL is: /esop/toolkit/negotiation/rfq/publicRfqSummaryReport.do?rfqId=rfq_229969
0 голосов
/ 18 октября 2019

Для get_attribute:

Я думаю, что вы получите неправильный элемент без атрибута 'onclick'.

Вы должны расширить селектор css и подтвердить, что он найдет только один элемент.


Для current_url:

Сначала вы должны переключиться в новое окно. Попробуйте использовать следующий код:

# window_handles[-1] refer to last window created.
browser.switch_to.window(browser.window_handles[-1])
print(browser.current_url)   
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...