LoginSignup
4
7

More than 5 years have passed since last update.

[個人的メモ]python3でのwebページのスクレイピング

Posted at

スクレイピングをするときの注意点

ページのソースコードは右クリックをして、ページのソースを表示ではなく
スクリーンショット 2017-03-10 14.30.22.png

デベロッパーツールで表示された方を使う
スクリーンショット 2017-03-10 14.30.39.png

textの取り出し

<dt>価格<span class="tax">(税込)</span></dt>

のようにdtタグにspanタグが埋め込まれたもののテキスト取り出すには

source = '<dt>価格<span class="tax">(税込)</span></dt>'
soup = BeautifulSoup(source, "html.parser")
soup.text

.text指定やることで取り出せる

空白文字の削除

<dt>
    価格
    <span class="tax">(税込)</span>
</dt>

といったタグ内に空白文字がある場合

def remove_whitespace(str):
    return ''.join(str.split())

source = '<dt>価格<span class="tax">(税込)</span></dt>'
soup = BeautifulSoup(source, "html.parser")
remove_whitespace(soup.text)

とやって取り出せる

strip()とかでは中央にある空白は削除できないため、split()で空白文字を区切り文字として
.joinで結合している

BeautifulSoupでのfind

ある特定のクラスを探したい場合

一つの場合

soup.find(class_='hoge')

全てを検索する場合

soup.find_all(class_='hoge')

ある特定のidを探したい場合

一つの場合

soup.find(id='hoge')

全てを検索する場合

soup.find_all(id='hoge')

ある特定のタグを探したい場合

一つの場合

soup.find('hoge')

全てを検索する場合

soup.find_all('hoge')

またこれらは複数条件を同時にもできます

soup.find('hoge',class_='fuga)
4
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
7