【问题标题】:How can I change, add, or delete a tag's attribute如何更改、添加或删除标签的属性
【发布时间】:2019-08-27 15:49:09
【问题描述】:

我有一个带有两种“tr”标签的 html 文档。

<tr bgcolor="lightgrey">
<tr>

每个 tr 标签有 3-4 行代码,其中包含标签。由于某种原因,当我尝试访问属性时,我没有得到“lightgrey”,结果我要么得到错误,要么没有。 O 正在使用漂亮的汤来解析 html。

这是我尝试过的代码:

list = soup.find_all('tr')
    for item in list:
        print(item.attrib) #continuously prints none

我尝试使用

访问该属性
list = soup.find_all('tr')
        for item in list:
            print(item.find('tr')['bicolor'])

但我不断收到“NoneType 对象没有属性”或不可下标

我希望能够访问标签的属性,读取它,并根据其原始颜色将双色更改为所需的颜色。

【问题讨论】:

  • 你能分享一个网址吗?

标签: python html beautifulsoup attributes tags


【解决方案1】:

看看它是否这样工作:

my_list = soup.find_all("tr") #it's not a good idea to use a word like 'list' as a variable name...
for item in my_list:
   if len(item.attrs)>0: 
       print(item['bgcolor'])

输出:

浅灰色

【讨论】:

    猜你喜欢
    • 2023-03-11
    • 2016-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-03
    • 1970-01-01
    相关资源
    最近更新 更多