iT邦幫忙

4

請問python爬取google的圖片程式


import requests

import urllib.request

from bs4 import BeautifulSoup

import os

import time




word = input('Input key word: ')
url = 'https://www.google.com.tw/search?q='+word+' &rlz=1C1CAFB_enTW617TW621&source=lnms&tbm=isch&sa=X&ved=0ahUKEwienc6V1oLcAhVN-WEKHdD_B3EQ_AUICigB&biw=1128&bih=863'

photolimit = 10



headers = {'User-Agent': 'Mozilla/5.0'}

response = requests.get(url,headers = headers) #使用header避免訪問受到限制

soup = BeautifulSoup(response.content, 'html.parser')

items = soup.find_all('img')

folder_path ='./photo/'

if (os.path.exists(folder_path) == False): #判斷資料夾是否存在

    os.makedirs(folder_path) 



for index , item in enumerate (items):

    if (item and index < photolimit ):

        html = requests.get(item.get('src')) 

        img_name = folder_path + str(index + 1) + '.png'



        with open(img_name,'wb') as file: #以byte的形式將圖片數據寫入

            file.write(html.content)

            file.flush()

        file.close() 

        print('第 %d 張' % (index + 1))

        time.sleep(1)



print('Done')
 

請問我這個程式哪裡出問題?我記得幾個月前還能用啊?

錯誤訊息:
https://ithelp.ithome.com.tw/upload/images/20200114/20124260jBFJMQuBvH.jpg

有錯誤訊息嗎?
看起來是 google 改變 img href 的格式了
html = requests.get('https://www.google.com.tw/' + item.get('src'))
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

2 個回答

0
wesley41616
iT邦新手 5 級 ‧ 2020-01-14 14:15:43

html = requests.get('https://www.google.com.tw/' + item.get('src'))

25285132 iT邦新手 5 級 ‧ 2020-01-14 18:46:25 檢舉

https://ithelp.ithome.com.tw/upload/images/20200114/201242609w5D7nw5Ma.jpg
顯示這個錯誤訊息

3
ccutmis
iT邦高手 2 級 ‧ 2020-01-14 14:18:55

建議改用requests_html 土砲解決方案 提供您參考
(註: 安裝requests_html套件 pip install requests_html )

# -*- coding: utf-8 -*-
from requests_html import HTMLSession
import re,os,pathlib,base64

#如果 DOWNLOAD 資料夾不存在就新建
base_dir = os.path.dirname(os.path.realpath(__file__))+"\\"
img_dir=base_dir+"DOWNLOAD\\"
pathlib.Path(img_dir).mkdir(parents=True, exist_ok=True)

#清除 DOWNLOAD 資料夾裡的 jpg 及 png 檔
filelist = [ f for f in os.listdir(img_dir) if f.endswith(".jpg") or f.endswith(".gif") or f.endswith(".png")]
for f in filelist:
    os.remove(os.path.join(img_dir, f))

word = input('Input key word: ')
url = 'https://www.google.com.tw/search?q='+word+' &rlz=1C1CAFB_enTW617TW621&source=lnms&tbm=isch&sa=X&ved=0ahUKEwienc6V1oLcAhVN-WEKHdD_B3EQ_AUICigB&biw=1128&bih=863'

session = HTMLSession()
r = session.get(url)
r.html.render(sleep=3,scrolldown=1,wait=2)
img_arr=r.html.find("img")
img_no=0
for i in img_arr:
  tmp_content=''
  try:
    tmp_content=(i.attrs['src'])
  except:
    pass
  finally:
    if tmp_content!='' and tmp_content.find('http')==-1 and tmp_content.find('/images')==-1:
      if img_no>0:
        if tmp_content.find("jpeg")>-1:
          img_type='.jpg'
        elif tmp_content.find("gif")>-1:
          img_type='.gif'
        else:
          img_type='.png'
        img_url=img_dir+'img'+str(img_no)+img_type
        print(img_url)
        with open(img_url,'wb') as file:
          base64_data = re.sub('^data:image/.+;base64,', '', tmp_content)
          byte_data = base64.b64decode(base64_data)
          file.write(byte_data)
          file.flush()
        file.close() 
      img_no=img_no+1

註: 上面的demo是在Windows寫的,如果你的os是linux或macOS 只需把路徑字串裡的"\"改成"/",應該是能正常work。

看更多先前的回應...收起先前的回應...
25285132 iT邦新手 5 級 ‧ 2020-01-14 18:43:59 檢舉

我按照你的代碼直接複製上去卻顯示這個?
https://ithelp.ithome.com.tw/upload/images/20200114/20124260fRMEmDsFDf.jpg

ccutmis iT邦高手 2 級 ‧ 2020-01-14 18:57:41 檢舉

你是用CMD執行python的嗎 不是的話請試著用CMD執行 例如:
python yourcode.py[enter]

25285132 iT邦新手 5 級 ‧ 2020-01-14 19:17:21 檢舉

https://ithelp.ithome.com.tw/upload/images/20200114/20124260NEPCjParNA.jpg
用命令提示字元沒法執行啊?

ccutmis iT邦高手 2 級 ‧ 2020-01-14 19:42:03 檢舉

Download Python3.7+
https://www.python.org/downloads/
安裝過程中有個地方要記得勾(加到path變數)

安裝好Python後開啟cmd 輸入 python --version[enter]
(可以執行的話它會秀出你安裝的python版本)

接著輸入 pip install requests_html[enter]
安裝requests_html模組,假設上列動作都順利完成的話,應該就能正常在cmd底下執行。

這種基本中的基本讓我有點不知道該怎麼回答了.../images/emoticon/emoticon77.gif

25285132 iT邦新手 5 級 ‧ 2020-01-14 20:10:02 檢舉

成功了!非常感謝!

ccutmis iT邦高手 2 級 ‧ 2020-01-14 20:24:03 檢舉

/images/emoticon/emoticon82.gif

marlin12 iT邦研究生 5 級 ‧ 2020-01-15 19:35:50 檢舉

/images/emoticon/emoticon01.gif

ccutmis iT邦高手 2 級 ‧ 2020-01-15 20:25:55 檢舉

我要發表回答

立即登入回答