2017-03-19 1 views
1
나는이 HTML 코드에서 말 미국과 캐나다를 인쇄해야

에 대한 BS4를 사용하십니까? 나는 그것을 봤지만 아무것도 유용한 것을 발견하지 못했습니다.파이썬 중첩 된 html 태그

+0

정확하게 당신이 시도 무엇을하고의 문제는 무엇인가? 가능성이있는 것처럼 대답이 "아무것도"아닌 경우, 멀리 가서 변경하십시오. – jonrsharpe

+0

지금까지 해보신 것은 무엇입니까? 귀하의 bs4 코드는 무엇입니까? – Soviut

답변

0

이것이 전부라면 각 태그에 대해 get_text를 사용할 수 있습니다. 텍스트를 얻으려면이

from bs4 import BeautifulSoup 
html="""<div class="txt-block"> 
    <h4 class="inline">Country:</h4> 
     <a href="/search/title?country_of_origin=us&amp;ref_=tt_dt_dt" itemprop="url">USA</a> 
       <span class="ghost">|</span> 
     <a href="/search/title?country_of_origin=ca&amp;ref_=tt_dt_dt" itemprop="url">Canada</a> 
    </div>""" 
soup = BeautifulSoup(html, 'html.parser') 
[atag.get_text() for atag in soup.find_all('a')] 
0

을 시도하십시오, 다음 코드는 작동합니다

from bs4 import BeautifulSoup 
html_string = """<div class="txt-block"> 
    <h4 class="inline">Country:</h4> 
     <a href="/search/title?country_of_origin=us&amp;ref_=tt_dt_dt" itemprop="url">USA</a> 
       <span class="ghost">|</span> 
     <a href="/search/title?country_of_origin=ca&amp;ref_=tt_dt_dt" itemprop="url">Canada</a> 
    </div>""" 

soup = BeautifulSoup(html_string) 
print([node.string for node in soup.find_all('a', attrs={"itemprop" : "url"})]) 

위의 코드는 발생합니다 :

[u'USA', u'Canada'] 

당신은 BeautifulSoup로 Documentation here를 참조 할 수 있습니다. 그것은 사용하기 쉽고 간단합니다.

또한 lxml의 도움으로이 작업을 수행합니다.이 작업은 BeautifulSoup보다 훨씬 빠릅니다.

from lxml import html 
html_string = """<div class="txt-block"> 
    <h4 class="inline">Country:</h4> 
     <a href="/search/title?country_of_origin=us&amp;ref_=tt_dt_dt" itemprop="url">USA</a> 
       <span class="ghost">|</span> 
     <a href="/search/title?country_of_origin=ca&amp;ref_=tt_dt_dt" itemprop="url">Canada</a> 
    </div>""" 

root = html.fromstring(html_string) 
print(root.xpath('//a[@itemprop="url"]//text()')) 

도됩니다 어떤 :

['USA', 'Canada'] 
0

간단한 방법 findAll 혼자 나라 이름을 추출 할 수 있습니다.

from bs4 import BeautifulSoup 
html =""" 
<div class="txt-block"> 
    <h4 class="inline">Country:</h4> 
    <a href="/search/title?country_of_origin=us&amp;ref_=tt_dt_dt" itemprop="url">USA</a> 
    <span class="ghost">|</span> 
    <a href="/search/title?country_of_origin=ca&amp;ref_=tt_dt_dt" itemprop="url">Canada</a> 
</div> 
""" 
soup = BeautifulSoup(html,"html.parser") 
for i in soup.findAll("a"): 
    print(i.text) 

당신이 원하는 결과 줄 것이다 위의 코드의 실행 : 여기 파이썬 3의 솔루션 코드

USA 
Canada