웹 페이지의 소스 코드를 html 파일로 저장해야합니다. 그러나 웹 페이지를 보면 섹션이 많고 필요하지 않으며 기사 자체의 소스 코드 만 저장하려고합니다.파이썬 : 소스 코드의 일부를 긁어서 html로 저장
코드 :
from urllib.request import urlopen
page = urlopen('http://www.abcde.com')
page_content = page.read()
with open('page_content.html', 'wb') as f:
f.write(page_content)
내 코드에서 전체 소스 코드를 저장할 수 있습니다,하지만 어떻게 난 그냥 내가 원하는 유일한 부분을 절약 할 수 있습니다?
설명 :
<div itemscope itemtype="http://schema.org/MedicalWebPage">
.
.
.
</div>
내가와이 태그 안에 소스 코드를 저장 태그의 문장을 추출 할 필요가있다.
내가 원하는 결과는 다음과 같이 저장하는 것입니다 :
<div itemscope itemtype="http://schema.org/MedicalWebPage">
<div class="col-md-12 col-xs-12" style="padding-left:10px;">
<h1 itemprop="name" class="page_article_title" title="Apple" id="mask">Apple</h1>
</div>
<!--Article Start-->
<section class="page_article_div" id="print">
<article itemprop="text" class="page_article_content">
<p>
<img alt="Apple" src="http://www.abcde.com/383741719.jpg" style="width: 300px; height: 200px;" /></p>
<p>
The apple tree (Malus pumila, commonly and erroneously called Malus domestica) is a deciduous tree in the rose family best known for its sweet, pomaceous fruit, the apple.</p>
<p>
It is cultivated worldwide as a fruit tree, and is the most widely grown species in the genus Malus.</p>
<p>
<strong><span style="color: #884499;">Appe is red</span></strong></p>
<ol>
<li>
Germanic paganism</li>
<li>
Greek mythology</li>
</ol>
<p style="text-align: right;">
【Jane】</p>
<p style="text-align: right;">
Credit : Wiki</p>
</article>
<div style="text-align:right;font-size:1.2em;"><a class="authorlink" href="http://www.abcde.com/web/online;url=http://61.66.117.1234/name=2017">2017</a></div>
<br />
<div style="text-align:right;font-size:1.2em;">【Thank you!】</div>
</section>
<!--Article End-->
</div>
['BeautifulSoup'] (https://www.crummy.com/software/BeautifulSoup/bs4/doc/)를 사용하십시오. –
@andrew_reece 내가 잘못 설명 했어, 미안. 나는 내가 필요한 문장을 추출하기 위해 beautifulsoup를 사용할 수 있다는 것을 알고 있지만, 이제는 위의 두 태그를 포함한 태그 안에 전체 소스 코드를 저장해야한다. – Makiyo
string1을 openning div 태그 줄에 할당하고 string2를 할당한다. finnaly string1을 추출하고, string2를 하나의 문자열에 풀어서 파일로 저장합니다. –