簡體   English   中英

使用 selenium 查找所有帶有 href 屬性的標簽

[英]Find all tags with href attribute using selenium

我想使用 selenium 查找網頁的所有具有“href”屬性的標簽。 但是可用的方法是特定於標簽的。 示例:find_element_by_*() 我希望代碼獨立於標簽。 即獲取所有具有 href 屬性的標簽。 任何幫助,將不勝感激!

您可以使用 XPath 或 CSS 選擇器。

>>> driver.get('https://www.python.org')
>>>
>>> len(driver.find_elements_by_css_selector('[href]'))
241
>>> len(driver.find_elements_by_xpath('//*[@href]'))
241

https://selenium-python.readthedocs.io/locating-elements.html#locating-by-xpath

https://selenium-python.readthedocs.io/locating-elements.html#locating-elements-by-css-selectors

嘗試這個:

from selenium import webdriver

driver = webdriver.Chrome()
driver.get('https://google.com')
elements = driver.find_elements_by_xpath('//*[@href]')
all_tags = [el.tag_name for el in elements]
print(all_tags)
driver.quit()

我將參考這篇文章: https://stackoverflow.com/a/27307235/15303240

無法使用 selenium webdriver API,但您可以執行 javascript 代碼來獲取所有屬性

driver.execute_script('var items = {}; for (index = 0; index < arguments[0].attributes.length; ++index) { items[arguments[0].attributes[index].name] = arguments[0].attributes[index].value }; return items;', element)

演示:

>>> from selenium import webdriver
>>> from pprint import pprint
>>> driver = webdriver.Firefox()
>>> driver.get('https://stackoverflow.com')
>>> 
>>> element = driver.find_element_by_xpath('//div[@class="network-items"]/a')
>>> attrs = driver.execute_script('var items = {}; for (index = 0; index < arguments[0].attributes.length; ++index) { items[arguments[0].attributes[index].name] = arguments[0].attributes[index].value }; return items;', element)
>>> pprint(attrs)
{u'class': u'topbar-icon icon-site-switcher yes-hover js-site-switcher-button js-gps-track',
 u'data-gps-track': u'site_switcher.show',
 u'href': u'//stackexchange.com',
 u'title': u'A list of all 132 Stack Exchange sites'}

為了完整起見,另一種解決方案是獲取標簽的outerHTML並使用 HTML 解析器解析屬性。 示例(使用BeautifulSoup ):

>>> from bs4 import BeautifulSoup
>>> html = element.get_attribute('outerHTML')
>>> attrs = BeautifulSoup(html, 'html.parser').a.attrs
>>> print(attrs)
{u'class': [u'topbar-icon',
            u'icon-site-switcher',
            u'yes-hover',
            u'js-site-switcher-button',
            u'js-gps-track'],
 u'data-gps-track': u'site_switcher.show',
 u'href': u'//stackexchange.com',
 u'title': u'A list of all 132 Stack Exchange sites'}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM