【问题标题】:BeautifulSoup - Adding attributes on ResultsetBeautifulSoup - 在结果集上添加属性
【发布时间】:2017-10-18 08:13:43
【问题描述】:

这是我要抓取的 html 结构:

<div class='schedule-lists'>
    <ul>
        <li>...</li>
            <ul>
                <li>...</li>
                    <ul class='showtime-lists'>
                        <li>...</li>
                            <li><a auditype="N" cinema="0100" href="javascript:void(0);" >12:45</a></li>
                        <li>...</li>  -- (same structured as above)
                        <li>...</li>  -- (same structured as above)

        <li>...</li> -- (same structured as above)
        <li>...</li> -- (same structured as above)

这是我的代码:

from requests import get
from bs4 import BeautifulSoup
response = get('www.example.com')
response_html = BeautifulSoup(response.text, 'html.parser')
containers = response_html.find_all('ul', class_='showtime-lists')
#print(containers)
[<ul class="showtime-lists">
<li><a auditype="N" cinema="0100" href="javascript:void(0);" >12:45</a></li>

如何在我的结果集容器上添加属性?就像添加 movietitle="Logan" 所以它变成:

<li><a movietitle="Logan" auditype="N" cinema="0100" href="javascript:void(0);" >12:45</a></li>

我最好的尝试是使用 .append 方法,但它可以完成,因为 ResultSet 就像字典一样

【问题讨论】:

    标签: html python-3.x web-scraping beautifulsoup


    【解决方案1】:

    你可以试试这个:

    ...
    a = find_all('a')
    i = 0
    for tag in a:
        a[i]['movietitle'] = 'Logan'
        i += 1
    print str(a)
    

    【讨论】:

      猜你喜欢
      • 2013-07-04
      • 1970-01-01
      • 2016-04-26
      • 2018-06-12
      • 2010-12-14
      • 1970-01-01
      • 2018-07-17
      • 2020-03-22
      • 2015-04-08
      相关资源
      最近更新 更多