0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Python スクレイピング 勉強 2

0
Posted at

前回までの記事


1. 初回 https://qiita.com/coogelu/items/ddab4878cb6ed8fc55b8

目的

  • 最後にPythonを触ったのが、1年前とかなのでこの勉強を通し思い出す
  • 思い出しついでにスクレイピングについて勉強する
  • コードを書くことそのものを勉強する

環境

  • Windows11 Pro
  • Python 3.12.3
  • VSCode

今回の学習内容

  • 前回のスクリプトの訂正
  • テキストファイルへのR/Wについて

スクリプト(前回の訂正について)

全体

import requests
from bs4 import BeautifulSoup

url = "https://www.yahoo.co.jp/"
html = requests.get(url)

soup = BeautifulSoup(html.content, "html.parser")
main_news = soup.find(class_="_2jjSS8r_I9Zd6O9NFJtDN-")

for news in main_news.find_all("a"):
    if news.text == "NEW":
        continue
    
    print(news.text)

変更点

  • for文で指定するhtmlタグをspanタグからaタグに変更
  • 上記の変更に伴い、更新日時が出力されないように処理するif文を削除

原因

  • HTMLをよく見ると、更新日時を表示させているspanタグは主要ニュースのツリー下すぐに入っていた
  • aタグで見ると、更新日時を含まないタグの下からニュースの見出しを取得できた

スクリプト(ファイル操作について)

全体

テキストファイルに書き込む

with open("sample.txt", "w", encoding="utf-8") as f:
    f.write("Hello, ")

テキストファイルに追記する

with open("sample.txt", "a", encoding="utf-8") as f:
    f.write("world.\n")

テキストファイルを読み込む

with open("sample.txt", "r", encoding="utf-8") as f:
    text = f.read()

各スクリプトの説明

テキストファイルに書き込む

with open("sample.txt", "w", encoding="utf-8") as f:
    f.write("Hello, ")

withについて

withについては知っていたのですが、完全に忘れていたので今回学習しなおしたようなものです。
これをすることでopen()したファイルをclose()しなくてもよくなるらしいです。
自動で閉じてくれるんだって。
逆に、withを使わない場合は下記みたいに書くらしい。

f = open("sample.text, "r", encoding="utf-8") as f:
    f.write("Hello, world")
    f.close()

だいたいはwithで書いちゃうだろうけど、覚えておこうと思う。

テキストファイルに追記する

with open("sample.txt", "a", encoding="utf-8") as f:
    f.write("world.\n")

既存のテキストに書き込むことができるらしい
open()の第二引数をw → aにすることで追記にできるんだとさ

テキストファイルを読み込む

with open("sample.txt", "r", encoding="utf-8") as f:
    text = f.read()

テキストをpythonで扱えるように読み込ませるよ。
open()の第二引数をrにすることでできるらしい。
読み込ませ方は変数に代入するんだとさ。
このままprint()してあげれば表示できるよ。

まとめ

スクレイピングってPythonだけじゃなくてHTMLも読めないといけないんだね。
なんか超技術でいい感じに目的の箇所だけ抜けるんだと思ってた。

ファイル操作を理解するのがめんどくさくて、ふわっとも理解してなかったけど今回で初歩は分かったと思うので、今後は怖くないはず。

めでたしめでたし。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?