・プログラミング
寝る前から半分くらい映画見ながらダラダラプログラミング。
映画が思いの外面白かったので実質集中してたのは合計で3時間くらいか。
昨日のやつを拡張
・検索対象のKINZA画像検索のページ範囲を任意に設定できるように(↓では10に)
・timeモジュールでダウンロード間隔をあけるように
それだけ。それだけだけど3時間以上(主に上)かかった。
まだイマイチ自分のプログラムの挙動がわかってない。
import os import time import urllib from urllib.request import urlopen from bs4 import BeautifulSoup sleep_time_sec = 1 #ローカルの保存先 dst_dir = r'C:\Users\Administrator\Desktop\sf2' #検索する用語を指定 gazo = '山田勝己' #日本語でもエラーが起きないようにする quote = urllib.parse.quote(gazo) #検索ページ数 ※0以下は入れちゃだめ page = 10 #nページ目までの検索ページURLが入ったリスト nlist = [] #ローカルにダウンロードするためのもの、ネットからの拾い物 def download_file(url, dst_path): try: #URL開く with urllib.request.urlopen(url) as web_file: #dataに読みとったものを入れとく data = web_file.read() #書く with open(dst_path, mode='wb') as local_file: local_file.write(data) except urllib.error.URLError as e: print(e) #ローカルにダウンロードするためのもの、ディレクトリを指定する、ネットからの拾い物 def download_file_to_dir(url, dst_dir): #パスをつなげてダウンロード先を指定するらしい? download_file(url, os.path.join(dst_dir, os.path.basename(url))) def pagelist(page): for i in range(page): i += 1 x = 'https://search.kinza.jp/img/?q=' + str(quote) + '&spl=&page=' + str(i) + '&fr=newtab' nlist.append(x) #nページ目までの検索ページURLが入ったリストを作成。nlistに格納。 pagelist(page) plist = [] for i in nlist: html = urllib.request.urlopen(i) #BeautifulSoupで解析 soup = BeautifulSoup(html, 'lxml') #Pには分析結果が入ってる p = soup.find_all("div", attrs={"class": "img_url hid"}) #URLの末尾が拡張子じゃないURLだとエラーが起きるので妥協してURLの末尾が.jpgのやつだけのリストを作る for o in p: #余計なHTMLタグを消す i = o.string #print(i) if i.endswith(".jpg"): plist.append(i) print(plist) for u in plist: url = u #download_file_to_dir(url, dst_dir) download_file_to_dir(url, dst_dir) time.sleep(sleep_time_sec)
試してみたが、たまに403とか404が出てくると(処理自体は止まらないが)そこはダウンロードできない。
それだけならいいが、日本語ドメインややたら長過ぎのURL(?)にさしかかったとき(無効な引数どうとかのエラーが出る)にエラーで処理が止まってしまう。これらをスルーする処理を方法をまた調べるのか・・・やっぱきついなプログラミング。
さてもう今日はいいかな。
以上
1年前
kusomamiren.hatenablog.com