<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Beautifulsoup</title>
	<atom:link href="https://javeo.jp/tag/beautifulsoup/feed/" rel="self" type="application/rss+xml" />
	<link>https://javeo.jp</link>
	<description>ほどほどレベルのプログラミング</description>
	<lastBuildDate>Sun, 09 Jun 2024 16:40:48 +0000</lastBuildDate>
	<language>ja</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9.4</generator>

<image>
	<url>https://javeo.jp/wp-content/uploads/2025/08/cropped-ExcelPython_future-32x32.jpg</url>
	<title>Beautifulsoup</title>
	<link>https://javeo.jp</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>【Python】Beautifulsoupでタグがない部分を取得する</title>
		<link>https://javeo.jp/beautifulsoup-sample1/</link>
					<comments>https://javeo.jp/beautifulsoup-sample1/#respond</comments>
		
		<dc:creator><![CDATA[ジャベ雄]]></dc:creator>
		<pubDate>Fri, 03 Nov 2023 23:00:00 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[Beautifulsoup]]></category>
		<category><![CDATA[スクレイピング]]></category>
		<guid isPermaLink="false">https://javeo.jp/?p=1469</guid>

					<description><![CDATA[目次 &#8220;タグがない部分&#8221;の具体例取得しようとした時の問題タグ間の文字を取得する例separatorを設定してsplitで無理やり区切るちなみにget_textの仕様要らない部分を削除する初期値cl [&#8230;]]]></description>
										<content:encoded><![CDATA[<div class="codoc-evacuations" style="display:none;" data-shortcode=""></div>
<div class="wp-block-cocoon-blocks-info-box block-box primary-box">
<p>直接指定する方法はまだわかっていませんが、暫定的に取得する方法があったのでまとめています</p>



<p>ちなみに私は&#8221;find&#8221;ではなく&#8221;select&#8221;派です</p>
</div>




  <div id="toc" class="toc tnt-number toc-center tnt-number border-element"><input type="checkbox" class="toc-checkbox" id="toc-checkbox-2" checked><label class="toc-title" for="toc-checkbox-2">目次</label>
    <div class="toc-content">
    <ol class="toc-list open"><li><a href="#toc1" tabindex="0">&#8220;タグがない部分&#8221;の具体例</a></li><li><a href="#toc2" tabindex="0">取得しようとした時の問題</a></li><li><a href="#toc3" tabindex="0">タグ間の文字を取得する例</a><ol><li><a href="#toc4" tabindex="0">separatorを設定してsplitで無理やり区切る</a><ol><li><a href="#toc5" tabindex="0">ちなみにget_textの仕様</a></li></ol></li><li><a href="#toc6" tabindex="0">要らない部分を削除する</a><ol><li><a href="#toc7" tabindex="0">初期値</a></li><li><a href="#toc8" tabindex="0">clear()</a></li><li><a href="#toc9" tabindex="0">extract()</a></li><li><a href="#toc10" tabindex="0">decompose()</a></li><li><a href="#toc11" tabindex="0">replace_with()</a></li></ol></li><li><a href="#toc12" tabindex="0">next系、previous系で取得する</a></li></ol></li><li><a href="#toc13" tabindex="0">あとがき</a></li></ol>
    </div>
  </div>

<h2 class="wp-block-heading"><span id="toc1">&#8220;タグがない部分&#8221;の具体例</span></h2>



<p>&#8220;タグがない部分&#8221;だとイマイチ伝わらないのでサンプルを</p>



<p>ソースにするとこれ</p>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-html" data-file="sample_html" data-lang="HTML"><code>&lt;div class=&quot;test&quot;&gt;
    ①ここを取得したい&lt;p class=one&gt;、ここはいらない、けど&lt;/p&gt;②ここも取得する
    &lt;p class=two&gt;③ここも取得したい&lt;/p&gt;
    &lt;p class=three&gt;ここもいらない&lt;/p&gt;
&lt;/div&gt;</code></pre></div>



<p>htmlなので本当に&#8221;タグがない&#8221;なんてことはないんですが、<span class="marker-under">ピンポイントで指定するためのタグがない</span>ってのが正しい表現</p>



<p>スクレイピングしてると何度かであって苦慮したのでまとめてみました</p>



<p>↓は練習とかに使いたい人用</p>



<div class="test">
    ①ここを取得したい<p class=one>、ここはいらない、けど</p>②ここも取得する
    <p class=two>③ここも取得したい</p>
    <p class=three>ここもいらない</p>
</div>



<h2 class="wp-block-heading"><span id="toc2">取得しようとした時の問題</span></h2>



<p>まず簡単なところで③の取得から</p>



<p>基本的な方法なのであえて説明する必要もないかと</p>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-python" data-lang="Python"><code>print(soup.select_one(&#39;div.test &gt; p.two&#39;).get_text())
&gt;&gt;③ここも取得したい</code></pre></div>



<p>問題は①と②の取得方法、、</p>



<p>当該箇所にタグがないので&#8221;find&#8221;や&#8221;select&#8221;で指定できない（と思う）</p>



<p>じゃあどうするのってのがここから</p>



<h2 class="wp-block-heading"><span id="toc3">タグ間の文字を取得する例</span></h2>



<h3 class="wp-block-heading"><span id="toc4">separatorを設定してsplitで無理やり区切る</span></h3>



<p>まずはソースから</p>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-python" data-lang="Python"><code>print(soup.select_one(&#39;div.test&#39;).get_text(separator=&#39;||&#39;, strip=True).split(&#39;||&#39;))
&gt;&gt;[&#39;①ここを取得したい、&#39;, &#39;②ここはいらない、けど&#39;, &#39;③ここも取得する&#39;, &#39;④ここも取得したい&#39;, &#39;⑤ここもいらない&#39;]</code></pre></div>



<p>Beautifulsoupを使い始めてすぐの頃&#8221;get_text&#8221;の引数に&#8221;separator&#8221;と&#8221;strip&#8221;があるのを知らなかったわけですが、&#8221;separator&#8221;を設定するとタグ間に無理やり指定の文字を挿入できます</p>



<p>つまり、&#8221;separator&#8221;に適当な文字を設定して、同じ文字で&#8221;split&#8221;すればリストにできるのであとはインデックスを指定してあげればOK</p>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-python" data-lang="Python"><code>print(soup.select_one(&#39;div.test&#39;).get_text(separator=&#39;||&#39;, strip=True).split(&#39;||&#39;)[0])
&gt;&gt;&#39;①ここを取得したい、&#39;
print(soup.select_one(&#39;div.test&#39;).get_text(separator=&#39;||&#39;, strip=True).split(&#39;||&#39;)[2])
&gt;&gt;&#39;③ここも取得する&#39;
print(soup.select_one(&#39;div.test&#39;).get_text(separator=&#39;||&#39;, strip=True).split(&#39;||&#39;)[3])
&gt;&gt;&#39;④ここも取得したい&#39;</code></pre></div>



<h4 class="wp-block-heading"><span id="toc5">ちなみにget_textの仕様</span></h4>



<p>どうやって&#8221;separator&#8221;を挿入してるんだと思ったら、そもそも<span class="marker-under-red">Beautifulsoupはelement（≒タグ）で分割されている仕様</span>で、初期値空白でjoinで結合しているので値を指定すれば挟み込めるわけですね</p>



<p>ついでに引数の&#8221;strip&#8221;がなんでタグ毎にstripが適用されるかと言うとこの仕様によるものでした</p>



<p>（たまにパッケージの仕様を調べるとプログラムの作り方の参考になりますよね）</p>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-python" data-lang="Python"><code>def get_text(self, separator=&quot;&quot;, strip=False, types=default):
    &quot;&quot;&quot;Get all child strings of this PageElement, concatenated using the
    given separator.

    :param separator: Strings will be concatenated using this separator.

    :param strip: If True, strings will be stripped before being
        concatenated.

    :param types: A tuple of NavigableString subclasses. Any
        strings of a subclass not found in this list will be
        ignored. Although there are exceptions, the default
        behavior in most cases is to consider only NavigableString
        and CData objects. That means no comments, processing
        instructions, etc.

    :return: A string.
    &quot;&quot;&quot;
    return separator.join([s for s in self._all_strings(strip, types=types)])</code></pre></div>



<h3 class="wp-block-heading"><span id="toc6">要らない部分を削除する</span></h3>



<p>この方法だと要素を削除するのでやり方次第では順番を間違えると④が取得できないのでご注意</p>



<p>削除の仕方はいくつかあるので下記からお好きな方法を</p>



<h4 class="wp-block-heading"><span id="toc7">初期値</span></h4>



<p>参考にするため、まず何もせずに当該箇所を指定してprintした結果を</p>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-python" data-lang="Python"><code>print(soup.select_one(&#39;div.test&#39;))
&gt;&gt;&lt;div class=&quot;test&quot;&gt;
    ①ここを取得したい、&lt;p class=&quot;one&quot;&gt;②ここはいらない、けど&lt;/p&gt;③ここも取得する
    &lt;p class=&quot;two&quot;&gt;④ここも取得したい&lt;/p&gt;
&lt;p class=&quot;three&quot;&gt;⑤ここもいらない&lt;/p&gt;
&lt;/div&gt;</code></pre></div>



<h4 class="wp-block-heading"><span id="toc8">clear()</span></h4>



<p>指定したタグ内の文字だけ消してタグは残るパターン</p>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-python" data-lang="Python"><code>soup.select_one(&#39;div.test &gt; p.one&#39;).clear()
print(soup.select_one(&#39;div.test&#39;))
&gt;&gt;&lt;div class=&quot;test&quot;&gt;
    ①ここを取得したい、&lt;p class=&quot;one&quot;&gt;&lt;/p&gt;③ここも取得する
    &lt;p class=&quot;two&quot;&gt;④ここも取得したい&lt;/p&gt;
&lt;p class=&quot;three&quot;&gt;⑤ここもいらない&lt;/p&gt;
&lt;/div&gt;</code></pre></div>



<p>&#8220;②ここはいらない、けど&#8221;の文字だけが削除されている</p>



<h4 class="wp-block-heading"><span id="toc9">extract()</span></h4>



<p>タグを削除しつつ、要素を取り出す　※つまり切り取りのようなもの</p>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-python" data-lang="Python"><code>element = soup.select_one(&#39;div.test &gt; p.one&#39;).extract()
print(element)
&gt;&gt;&lt;p class=&quot;one&quot;&gt;②ここはいらない、けど&lt;/p&gt;

print(soup.select_one(&#39;div.test&#39;))
&gt;&gt;&lt;div class=&quot;test&quot;&gt;
    ①ここを取得したい、③ここも取得する
    &lt;p class=&quot;two&quot;&gt;④ここも取得したい&lt;/p&gt;
&lt;p class=&quot;three&quot;&gt;⑤ここもいらない&lt;/p&gt;
&lt;/div&gt;</code></pre></div>



<p>タグごとelementに代入されていることがわかる</p>



<h4 class="wp-block-heading"><span id="toc10">decompose()</span></h4>



<p>タグを削除するのみ　※これがズバリ削除</p>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-python" data-lang="Python"><code>element = soup.select_one(&#39;div.test &gt; p.one&#39;).decompose()
print(element)
&gt;&gt;

print(soup.select_one(&#39;div.test&#39;))
&gt;&gt;&lt;div class=&quot;test&quot;&gt;
    ①ここを取得したい、、③けどここも取得する
    &lt;p class=&quot;two&quot;&gt;④ここも取得したい&lt;/p&gt;
&lt;p class=&quot;three&quot;&gt;⑤ここもいらない&lt;/p&gt;
&lt;/div&gt;</code></pre></div>



<p>こっちはelementをprintしても何もないので純粋に削除されていることがわかる</p>



<h4 class="wp-block-heading"><span id="toc11">replace_with()</span></h4>



<p>文字通り置き換える</p>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-python" data-lang="Python"><code>element = soup.select_one(&#39;div.test &gt; p.one&#39;).replace_with(&#39;[hgoe]&#39;)
print(element)
&gt;&gt;&lt;p class=&quot;one&quot;&gt;、ここはいらない、けど&lt;/p&gt;

print(soup.select_one(&#39;div.test&#39;))
&gt;&gt;&lt;div class=&quot;test&quot;&gt;
    ①ここを取得したい[hgoe]②ここも取得する
    &lt;p class=&quot;two&quot;&gt;④ここも取得したい&lt;/p&gt;
&lt;p class=&quot;three&quot;&gt;ここもいらない&lt;/p&gt;
&lt;/div&gt;</code></pre></div>



<p>extractと同じで置換前のelementは変数に代入する</p>



<p>つまり、置換後の文字を空白にすればextractと同じ結果になる</p>



<h3 class="wp-block-heading"><span id="toc12">next系、previous系で取得する</span></h3>



<p>指定したelementの前後が取得できる&#8221;next系&#8221;や&#8221;previous系&#8221;で無理矢理取得する</p>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-python" data-lang="Python"><code>print(soup.select_one(&#39;div.test&#39;).next_element.get_text())
&gt;&gt;&#39;\n    ①ここを取得したい&#39;

print(soup.select_one(&#39;div.test &gt; p.one&#39;).previous_element.get_text())
&gt;&gt;&#39;\n    ①ここを取得したい&#39;

print(soup.select_one(&#39;div.test &gt; p.one&#39;).next_sibling.get_text())
&gt;&gt;&#39;②ここも取得する\n    &#39;

print(soup.select_one(&#39;div.test &gt; p.two&#39;).previous_sibling.get_text())
&gt;&gt;&#39;②ここも取得する\n    &#39;</code></pre></div>



<p>これが一番真っ当な取得方法な気がする</p>



<h2 class="wp-block-heading"><span id="toc13">あとがき</span></h2>



<p>調べてもなかなか出てこない情報なので自分なりにまとめてみました</p>



<p>そもそもサイト構成としてどうなの？とは思うところですが、こちらがとやかく言う話ではないのでどうにかこねくり回して取得していきましょう</p>
]]></content:encoded>
					
					<wfw:commentRss>https://javeo.jp/beautifulsoup-sample1/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
