2017-07-06 42 views
0

タグ内にタグを取得する方法は?Python - BeautifulSoup、タグ内のタグを取得

<a href="/Archives/edgar/data/1085621/000108562117000004/actuacorp12312016.htm">actuacorp12312016.htm</a> 

私はこれらのようなタグがあります:

<td scope="row"><a href="/Archives/edgar/data/1085621/000108562117000004/actuacorp12312016.htm">actuacorp12312016.htm</a></td> 

が、私はその中のhrefタグの値が、主にHTMリンクをしたい:ここでTDタグのうち

<tr> 
<td scope="row">1</td> 
<td scope="row">10-K</td> 
<td scope="row"><a href="/Archives/edgar/data/1085621/000108562117000004/actuacorp12312016.htm">actuacorp12312016.htm</a></td> 
<td scope="row">10-K</td> 
<td scope="row">2724989</td> 
</tr> 
<tr class="blueRow"> 
<td scope="row">2</td> 
<td scope="row">EXHIBIT 21.1</td> 
<td scope="row"><a href="/Archives/edgar/data/1085621/000108562117000004/exhibit211q42016.htm">exhibit211q42016.htm</a></td> 
<td scope="row">EX-21.1</td> 
<td scope="row">21455</td> 
</tr> 
<tr> 
<td scope="row">3</td> 
<td scope="row">EXHIBIT 23.1</td> 
<td scope="row"><a href="/Archives/edgar/data/1085621/000108562117000004/exhibit231q42016.htm">exhibit231q42016.htm</a></td> 
<td scope="row">EX-23.1</td> 
<td scope="row">4354</td> 
</tr> 

すべてのタグを表示するコード:

あなたが最初にすべての tdのタグを取得するために find_allを使用して、これらのタグ内のアンカーを検索することができ
base_url = "https://www.sec.gov/Archives/edgar/data/1085621/000108562117000004/" \ 
       "0001085621-17-000004-index.htm" 
    response = requests.get(base_url) 
    base_data = response.content 
    base_soup = BeautifulSoup(base_data, "html.parser") 

答えて

1

links = [] 
for tag in base_soup.find_all('td', {'scope' : 'row'}): 
    for anchor in tag.find_all('a'): 
     links.append(anchor['href']) 

print(links) 

は出力:

['/Archives/edgar/data/1085621/000108562117000004/actuacorp12312016.htm', 
'/Archives/edgar/data/1085621/000108562117000004/exhibit211q42016.htm', 
... 
'/Archives/edgar/data/1085621/000108562117000004/acta-20161231_lab.xml', 
'/Archives/edgar/data/1085621/000108562117000004/acta-20161231_pre.xml'] 

あなたが少しフィルターを書くことができます必要に応じて非htmリンクを削除してください:

filtered_links = list(filter(lambda x: x.endswith('.htm'), links)) 

最初のリンクを取得するには、使用するケースに適したわずかに異なるバージョンがあります。

link = None 
for tag in base_soup.find_all('td', {'scope' : 'row'}): 
    children = tag.findChildren() 
    if len(children) > 0: 
     try: 
      link = children[0]['href'] 
      break 
     except: 
      continue 

print(link) 

これは、'/Archives/edgar/data/1085621/000108562117000004/acta-20161231_pre.xml'を印刷します。

+0

これは本当に良い解決策です。ありがとうございます。二度とループすることなくそれを行うには、とにかくありますか? forループを1つに減らす方法はありますか?たとえば、base_soup.find_all( 'td'、{'scope': 'row' {a}})のようなものです。 – Theo

+0

私はちょうど最初のhtmを望んでいます。 '/Archives/edgar/data/1085621/000108562117000004/actuacorp12312016.htm' – Theo

+1

@Theo数分で更新します。 –

関連する問題