Как создать ссылку, используя BeautifulSoup в Python?

1

Я пытаюсь создать HTML-страницу с таблицей с строками информации (тестовые примеры, неудачные, предупреждение, общее количество тестов). Я хочу, чтобы каждая строка в столбце "Тесты" была ссылкой на другую страницу. Как вы видите на изображении ниже, моя цель состоит в том, чтобы тест 1 был ссылкой. Изображение 174551 Ниже приведен код, который я написал, чтобы создать то, что вы видите на изображении. Благодарю.

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()

Ниже приведен код для создания ссылки, которую я взял из документации BeautifulSoup:

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()
  • 1
    что ты уже испробовал?
  • 0
    @PedroLobito Следующий код создает ссылку. Моя проблема состоит в том, как поместить это в таблицу, которую я создаю выше. из 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 = "Текст ссылки." original_tag # <b> <a href=" example.com"> текст ссылки . </a> </ b> f = open ("practice.html", 'w') f.write (soup.prettify ()) f.close ()
Показать ещё 5 комментариев
Теги:
beautifulsoup

1 ответ

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()
  • 0
    Спасибо. Это сработало.

Ещё вопросы

Сообщество Overcoder
Наверх
Меню