1

I'm trying to build a HTML page that has a table with rows of information (test cases, failed, warning, total # of tests) I want each row in the Test Cases column to be a link to another page. As you see in the image below, my goal is for Test 1 to be a link. enter image description here Below is the code that I wrote to build what you see in the image. Thanks.

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 = ["Test 1", str(5), str(3), str(6)]
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;'
        td.string = str(r)
        tr.append(td)
table.append(tr)

f.write(soup.prettify())
f.close()

Below is code for creating a link that I took from BeautifulSoup documentation:

from bs4 import BeautifulSoup

soup = BeautifulSoup("<b></b>", "lxml")
original_tag = soup.b

new_tag = soup.new_tag("a", href="http://www.example.com")
original_tag.append(new_tag)
original_tag
# <b><a href="http://www.example.com"></a></b>

new_tag.string = "Link text."
original_tag
# <b><a href="http://www.example.com">Link text.</a></b>
f = open("practice.html", 'w')
f.write(soup.prettify())
f.close()
7
  • 1
    What have you tried so far? Commented Sep 4, 2018 at 9:46
  • @PedroLobito Following code creates a link. My issue is how to put it into the table I create above. from bs4 import BeautifulSoup soup = BeautifulSoup("<b></b>", "lxml") original_tag = soup.b new_tag = soup.new_tag("a", href="example.com") original_tag.append(new_tag) original_tag # <b><a href="example.com"></a></b> new_tag.string = "Link text." original_tag # <b><a href="example.com">Link text.</a></b> f = open("practice.html", 'w') f.write(soup.prettify()) f.close() Commented Sep 4, 2018 at 10:24
  • Please update your question and add an example of the current and desired outputs. Commented Sep 4, 2018 at 10:26
  • I updated and boldfaced what my desired output is. My current output is what you see in the image. Commented Sep 4, 2018 at 10:29
  • We need code,not images. Commented Sep 4, 2018 at 10:32

2 Answers 2

2
# 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()
Sign up to request clarification or add additional context in comments.

Comments

1

How-to create a link using BeautifulSoup with label, attrs and target

import bs4

def a_href(url, label='', target='_blank', **kwargs):
    soup = bs4.BeautifulSoup('')
    combined_attrs = dict(target=target, href=url, **kwargs)
    tag = soup.new_tag(name='a', attrs=combined_attrs)
    tag.string = label
    return str(tag)  # or tag.prettify() for better formatting

Tests

class TestAHref(TestCase):

    def test_simple_link(self):
        self.assertEqual('<a href="www.ya.com" target="_blank"></a>', a_href('www.ya.com'))

    def test_link_with_attrs(self):
        self.assertEqual('<a href="ya.com" target="_self" x="1" y="2">XYZ</a>',
                         a_href('ya.com', x=1, y=2, target='_self', label='XYZ'))

2 Comments

could you add some human explanations of your solution? that would be great
@snoobdogg see the test cases!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.