私信  •  关注

kamal yassin

kamal yassin 最近创建的主题
kamal yassin 最近回复了
5 年前
回复了 kamal yassin 创建的主题 » 如何在python中使用beautifulsoup创建链接?
# This is updated code 
# You just need to add: a = bs4.Tag(td, name='a') to you'r code 
# Then you need to fill it:

    #     if index == 0: 
    #         a.attrs[''] = 'a href="http://www.yahoo.com"'
    #     a.string = r  
    #     td.append(a)



import bs4
f = open("practice.html", 'w')
html = """<html>
                      <body>
                          <table class="details" border="1" cellpadding="5" cellspacing="2" style="width:95%">
                          </table>
                      </body>
                  </html>"""
soup = bs4.BeautifulSoup(html, "lxml")
table = soup.find('table')
tr = bs4.Tag(table, name='tr')
HTMLColumns = ["Test Cases", "Failed", "Warning", "Total number of tests"]
for title in HTMLColumns:  # Add titles to each column
    td = bs4.Tag(tr, name='td')
    td.insert(0, title)
    td.attrs['style'] = 'background-color: #D6FCE9; font-weight: bold;'
    tr.append(td)
table.append(tr)
results = [str(k), str(v), str(0), str(v)]
tr = bs4.Tag(table, name='tr')
for index, r in enumerate(results):  # loop through whole list of issue tuples, and create rows
    td = bs4.Tag(tr, name='td')
    td.attrs['style'] = 'background-color: #ffffff; font-weight: bold;'
    a = bs4.Tag(td, name='a') 
    if index == 0:
        a.attrs[''] = 'a href="http://www.yahoo.com"'
    a.string = r
    td.append(a)
    tr.append(td)
table.append(tr)  # append the row to the table 
f.write(soup.prettify())
f.close()