繁体   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