【问题标题】:Extracting attributes from HTML tag using python selenium [duplicate]使用python selenium从HTML标签中提取属性[重复]
【发布时间】:2018-12-13 08:08:06
【问题描述】:

我正在使用以下 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 selenium


    【解决方案1】:

    使用.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'}
    

    【讨论】:

      猜你喜欢
      • 2019-05-13
      • 2018-05-07
      • 2011-12-14
      • 1970-01-01
      • 1970-01-01
      • 2017-06-02
      • 2016-09-20
      • 2021-09-08
      • 1970-01-01
      相关资源
      最近更新 更多