Skip to main content
 首页 » 编程设计

python之Selenium get_attribute ("id")

2025年01月19日10unruledboy

我正在使用 Selenium 和 Firefox 在 Python 中进行抓取。

我可以使用以下方法将我的 href 放入对象中:

HREF = node.find_elements_by_xpath(".//a") # Get the href's under the current node 

返回一堆 <a>看起来像这样的标签:

<a href="http://example.com" class="" title="The Link" data-ipshover="" data-ipshover-target="http://example.com/?preview=1" data-ipshover-timeout="1.5" id="ips_uid_1234_9"> 
    <span>The Link</span> 
</a> 

返回了多个链接,但如果我只关注第一个:

print dir(HREF[0]) 
print "#########" 
print HREF[0].text 
print HREF[0].id 
print HREF[0].get_attribute("title") 
print HREF[0].get_attribute("href") 
print HREF[0].get_attribute("data-ipshover-timeout") 
print HREF[0].get_attribute("id") 
print "#########" 

输出这个:

['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', 
'__format__', '__getattribute__', '__hash__', '__init__', '__module__', 
'__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', 
'__setattr__', '__sizeof__', '__str__', '__subclasshook__', 
'__weakref__', '_execute', '_id', '_parent', '_upload', '_w3c', 
'anonymous_children', 'clear', 'click', 
'find_anonymous_element_by_attribute', 'find_element', 
'find_element_by_class_name', 'find_element_by_css_selector', 
'find_element_by_id', 'find_element_by_link_text', 
'find_element_by_name', 'find_element_by_partial_link_text', 
'find_element_by_tag_name', 'find_element_by_xpath', 'find_elements', 
'find_elements_by_class_name', 'find_elements_by_css_selector', 
'find_elements_by_id', 'find_elements_by_link_text', 
'find_elements_by_name', 'find_elements_by_partial_link_text', 
'find_elements_by_tag_name', 'find_elements_by_xpath', 'get_attribute', 
'get_property', 'id', 'is_displayed', 'is_enabled', 'is_selected', 
'location', 'location_once_scrolled_into_view', 'parent', 'rect', 
'screenshot', 'screenshot_as_base64', 'screenshot_as_png', 'send_keys', 
'size', 'submit', 'tag_name', 'text', 'value_of_css_property'] 
######### 
The Link 
101b851e-67dd-4907-a2da-2dc1828cb09c 
The Link 
http://example.com 
1.5 
 
######### 

注意最后一个属性打印是空白的,什么时候应该返回ips_uid_1234_9 .所有其他属性都可以正常返回,所以我不确定为什么“id”不能正确返回。

请您参考如下方法:

我是个笨蛋。下次我需要使用相同的浏览器来抓取和查看源代码时...属性不会在 Firefox 中加载,但会在 Chrome 中加载。