Подтвердить что ты не робот

Как записать вывод в HTML файл с помощью Python BeautifulSoup

Я изменил HTML файл, удалив некоторые теги с помощью beautifulsoup. Теперь я хочу записать результаты обратно в HTML файл. Мой код:

from bs4 import BeautifulSoup
from bs4 import Comment

soup = BeautifulSoup(open('1.html'),"html.parser")

[x.extract() for x in soup.find_all('script')]
[x.extract() for x in soup.find_all('style')]
[x.extract() for x in soup.find_all('meta')]
[x.extract() for x in soup.find_all('noscript')]
[x.extract() for x in soup.find_all(text=lambda text:isinstance(text, Comment))]
html =soup.contents
for i in html:
    print i

html = soup.prettify("utf-8")
with open("output1.html", "wb") as file:
    file.write(html)

Так как я использовал soup.prettify, он генерирует HTML следующим образом:

<p>
    <strong>
     BATAM.TRIBUNNEWS.COM, BINTAN
    </strong>
    - Tradisi pedang pora mewarnai serah terima jabatan pejabat di
    <a href="#" onclick="location.href='http://batam.tribunnews.com/tag/polres/'; return false;" title="Polres">
     Polres
    </a>
    <a href="#" onclick="location.href='http://batam.tribunnews.com/tag/bintan/'; return false;" title="Bintan">
     Bintan
    </a>
    , Senin (3/10/2016).
   </p>

Я хочу получить результат как print i делаю:

<p><strong>BATAM.TRIBUNNEWS.COM, BINTAN</strong> - Tradisi pedang pora mewarnai serah terima jabatan pejabat di <a href="#" onclick="location.href='http://batam.tribunnews.com/tag/polres/'; return false;" title="Polres">Polres</a> <a href="#" onclick="location.href='http://batam.tribunnews.com/tag/bintan/'; return false;" title="Bintan">Bintan</a>, Senin (3/10/2016).</p>
<p>Empat perwira baru Senin itu diminta cepat bekerja. Tumpukan pekerjaan rumah sudah menanti di meja masing masing.</p>

Как я могу получить результат так же, как print i (т.е. Тег и его содержимое отображаются в одной строке)? Благодарю.

4b9b3361

Ответ 1

Просто преобразуйте экземпляр soup в строку и напишите:

with open("output1.html", "w") as file:
    file.write(str(soup))

Ответ 2

Используйте Unicode, чтобы быть в безопасности:

with open("output1.html", "w") as file:
    file.write(unicode(soup))

Ответ 3

Для Python 3 unicode был переименован в str, но мне пришлось передать аргумент кодирования для открытия файла, чтобы избежать UnicodeEncodeError.

with open("output1.html", "w", encoding='utf-8') as file:
    file.write(str(soup))