スクレイピングのコードを書いていたら途中で詰まってしまいました。
childに何も格納されていないのでそこが原因かと思いますが、hrefの属性指定してURLを格納するようにgetメソッドを書いたのに何故だ。。。と混乱しております。
解答よろしくお願いします。
Python
1#coding:utf-8 2 3import os 4from bs4 import BeautifulSoup 5import requests 6 7from PIL import Image 8import matplotlib.pyplot as plt 9import numpy as np 10 11import time 12 13from urllib import request 14 15import random 16 17def make_randname(): 18 source_str = '#$%&0123456789abcdefghijklmnopqrstuvwxyz' 19 random.choice(source_str) #a〜zでランダムに1文字 20 name = "".join([random.choice(source_str) for x in range(20)]) 21 return name + ".jpg" 22 23 24def getimg(link): 25 opener=request.build_opener() 26 opener.addheaders=[('User-Agent','Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1941.0 Safari/537.36')] 27 request.install_opener(opener) 28 # リンク先(一覧から一回飛んだページ)のContent-Body を取得する 29 print("anal") 30 response = requests.get(link) 31 body = response.content 32 soup = BeautifulSoup(body,"lxml") 33 a_tags = soup.find_all("a", target="_blank") 34 for a_tag in a_tags: 35 try: 36 src = a_tag["href"] 37 name = src.split("/")[-1] 38 if name.find(".jpg") < 0: break 39 name = make_randname() 40 request.urlretrieve(src, "./eroimages/"+name) 41 print("[success]: {}".format(name)) 42 time.sleep(0.05) 43 except: 44 print("[failed]: {}".format(name)) 45 46def geturl(link): 47 print("###############################################") 48 #print("Page: {}".format(i)) 49 # リンク先(一覧から一回飛んだページ)のBodyを取得する 50 aponse = requests.get(link) 51 52 # HTML をパースする 53 soup = BeautifulSoup(aponse.text, "lxml") 54 links = soup.find_all('a') 55 #print(links+"\n") 56 for link in links: 57 #title = link.find("strong") 58 child = link.get("href") 59 print("-----------------------------------------------") 60 #print("Title: {}".format(title.string)) 61 print(child) 62 getimg(child) 63 64def main(): 65 if not os.path.exists("./eroimages"): 66 os.mkdir("./eroimages") 67 for i in range(1,2): 68 link = "http://hnalady.com/page-{}.html".format(i) 69 geturl(link) 70 71if __name__ == "__main__": 72 main()
スクレイピング先のHTMLソースは
view-source:http://hnalady.com/page-0.html
です。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/10/29 08:50
2018/10/29 09:08 編集
2018/10/29 10:48 編集