Py学习  »  Python

使用python selenium从html标记提取属性[duplicate]

Kasi Visvanathan • 5 年前 • 1450 次点击  

我正在使用下面的python代码启动firefox网页。

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver= webdriver.Firefox()
driver.get("https://www.quora.com")

在启动之后,如果我知道这个标记的xpath。

<input  
class="text header_login_text_box ignore_interaction" 
type="text" 
name="email" tabindex="1"
data-group="js-editable"
placeholder="Email"
w2cid="wZgD2YHa18" 
id="__w2_wZgD2YHa18_email">

如果现在是属性名,我可以使用下面的命令在python上使用selenium webdriver提取属性。

dict['attribute'] = driver.find_element_by_xpath(x_path).get_attribute(attribute)

所以我的输出是

dict = { 'attribute':value}

请帮助我找出提取所有属性及其值的方法,即使我不知道它的所有属性是什么。我的预期产量是

dict = { "class" : "text header_login_text_box ignore_interaction" 
        "type" : "text" 
        "name":"email" 
         "tabindex" : "1"
        "data-group" : "js-editable"
        "placeholder" : "Email"
        "w2cid" : "wZgD2YHa18" 
        "id" : "__w2_wZgD2YHa18_email"
        }

我不知道有多远是可能的,但我期待像在字典中,我们可以提取数据,即使不知道的关键。 谢谢你

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/46230
 
1450 次点击  
文章 [ 1 ]  |  最新文章 5 年前
chitown88
Reply   •   1 楼
chitown88    6 年前

使用 .attrs

import bs4

html = '''<input  
class="text header_login_text_box ignore_interaction" 
type="text" 
name="email" tabindex="1"
data-group="js-editable"
placeholder="Email"
w2cid="wZgD2YHa18" 
id="__w2_wZgD2YHa18_email">'''

soup = bs4.BeautifulSoup(html, 'html.parser')


for tag in soup:
    attr_dict = (tag.attrs)

输出: print (attr_dict)

{'class': ['text', 'header_login_text_box', 'ignore_interaction'], 
'type': 'text', 
'name': 'email', 
'tabindex': '1', 
'data-group': 'js-editable', 
'placeholder': 'Email', 
'w2cid': 'wZgD2YHa18', 
'id': '__w2_wZgD2YHa18_email'}