2017-10-23 3 views
0

웹 페이지의 소스 코드를 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> 
+1

['BeautifulSoup'] (https://www.crummy.com/software/BeautifulSoup/bs4/doc/)를 사용하십시오. –

+0

@andrew_reece 내가 잘못 설명 했어, 미안. 나는 내가 필요한 문장을 추출하기 위해 beautifulsoup를 사용할 수 있다는 것을 알고 있지만, 이제는 위의 두 태그를 포함한 태그 안에 전체 소스 코드를 저장해야한다. – Makiyo

+0

string1을 openning div 태그 줄에 할당하고 string2를 할당한다. finnaly string1을 추출하고, string2를 하나의 문자열에 풀어서 파일로 저장합니다. –

답변

0

당신은 클래스 또는 태그 이름이나 ID로 태그의 속성을 사용하여 태그로 검색 할 수 있고, 그것을 지금까지 당신이 원하는를 포맷 것을 저장 아래 예와 같습니다.

driver = BeautifulSoup(yoursavedfile.read(), 'html.parser') 
tag_for_me = driver.find_elements_by_class_name('class_name_of_your_tag') 
print tag_for_me 

tag_for_me에 필수 코드가 있습니다.

+0

드라이버 = BeautifulSoup로 (PAGE_CONTENT'html.parser ') tag_for_me driver.find_elements_by_class_name = ('. page_article_title ') 인쇄 (tag_for_me) 오류가 두 번째 줄에 쉽게 발생'NoneType '개체 호출 가능하지 않습니다. – Makiyo

+0

아마도 속성을 통해 태그를 찾을 수 없습니다. 검색을 시도하십시오. 다른 부동산과 공유하거나 여기에 태그를 공유하십시오. – Shaamuji

0

Beautiful Soup을 사용하면 필요한 HTML 소스를 얻을 수 있습니다.

import requests 
from bs4 import BeautifulSoup 

target_class = "gb4" 
target_text = "Web History" 
r = requests.get("https://google.com") 
soup = BeautifulSoup(r.text, "lxml") 

for elem in soup.find_all(attrs={"class":target_class}): 
    if elem.text == target_text: 
     print(elem) 

출력 :

<a class="gb4" href="http://www.google.com/history/optout?hl=en">Web History</a>

+0

나는 당신을 시험해 보았지만 아무 것도 출력하지 못했습니다. 위에서 예상 한 출력을 업로드 했으므로 그 소스 코드를 모두 함께 가져올 수있는 방법이 있습니까? 즉, 기사 HTML을 먼저 저장 한 다음 콘텐츠 HTML (기사 제목과 내용이 다른 클래스에 있음)을 저장해야한다는 의미입니까? – Makiyo

+0

당신은 BeautifulSoup로하고 싶은 것을 할 수 있습니다. 문서를 읽고, 그들은 꽤 잘하고, 당신이 원하는 것을하는 방법을 보여줄 것입니다. 이 답변은 원래 요청에 대한 답변입니다. '이 태그를 사용하여 소스 코드를 저장해야하며 태그의 문장을 추출하지 않아야합니다.' –

0

사용 BeautifulSoup로는 삽입 할 HTML을 얻을 삽입 할 HTML을 얻을 수 있습니다. insert()를 사용하여 new_tag를 생성하십시오. 원본 파일을 덮어 씁니다. 여기

from bs4 import BeautifulSoup 
import requests 

#Use beautiful soup to get the place you want to insert. 
# div_tag is extracted div 
soup = BeautifulSoup("Your content here",'lxml') 
div_tag = soup.find('div',attrs={'class':'id=itemscope'}) 
#e.g 
#div_tag = <div id=itemscope itemtype="http://schema.org/MedicalWebPage"> 
</div> 


res = requests.get('url to get content from') 
soup1 = BeautifulSoup(res.text,'lxml') 
insert_data = soup1.find('your div/data to insert') 
#this will insert the tag to div_tag. You can overwrite this to your original page_content.html. 
div_tag.insert(3,insert_data) 
#div tag contains you desired output. Overwrite it to original file. 
0

내 자신의 솔루션 :

page = urlopen('http://www.abcde.com') 
page_content = page.read() 
soup = BeautifulSoup(page_content, "lxml") 
list = [] 
for tag in soup.select('div[itemtype="http://schema.org/MedicalWebPage"]'): 
    list.append(str(tag)) 
list2= (', '.join(list)) 
#print(list2)   
#print(type(list2)) 
with open('C:/html/try.html', 'w',encoding='UTF-8') as f: 
    f.write(list2) 

나는 그것만큼 간단하게하려고 노력하고 있으므로 초보자 오전,이 내 대답, 그것은 순간에 아주 잘 작동하고 :)