2016-11-10 16 views
6

Tôi sửa đổi tệp html bằng cách xóa một số thẻ bằng cách sử dụng beautifulsoup, sau đó tôi muốn ghi kết quả trở lại vào tệp html. mã của tôi:python BeautifulSoup Cách viết đầu ra vào tệp 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) 

nhưng kể từ khi tôi sử dụng soup.prettify, nó tạo ra html như thế này

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

Nhưng tôi có để có được kết quả như in tôi làm. như thế này:

<p><strong>BATAM.TRIBUNNEWS.COM, BINTAN</strong> - Tradisi pedang pora mewarnai serah terima jabatan pejabat di <a href="http://batam.tribunnews.com/tag/polres/" title="Polres">Polres</a> <a href="http://batam.tribunnews.com/tag/bintan/" 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> 

để biết cách tạo kết quả chính xác giống như in i. do đó, thẻ và nội dung của thẻ sẽ nằm trên cùng một dòng. Cảm ơn

Trả lời

15

Chỉ chuyển đổi phân biển soup chuỗi và ghi:

with open("output1.html", "w") as file: 
    file.write(str(soup)) 
Các vấn đề liên quan