我正在操縱一個代碼來從谷歌圖片搜索下載第 5 個圖片結(jié)果。但是,我遇到了以下代碼的兩個主要問題:from bs4 import BeautifulSoupimport urllib.requestimport osimport jsondef get_soup(url,header): return BeautifulSoup(urllib.request.urlopen(urllib.request.Request(url,headers=header)),'html.parser')query = input('>>> What image do you want? ') image_type=queryquery= query.split()query='+'.join(query)url="https://www.google.co.in/search?q="+query+"&source=lnms&tbm=isch"print ('>>> Base searching page from Google image:', url)DIR="C:/Users/alex/Desktop/try"header={'User-Agent':"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36"}soup = get_soup(url,header)ActualImages=[]# contains the link for Large original images, type of imagefor a in soup.find_all("div",{"class":"rg_meta"}): link , Type =json.loads(a.text)["ou"] ,json.loads(a.text)["ity"] ActualImages.append((link,Type))print('>>> Base page has', len(ActualImages),'images in total')if not os.path.exists(DIR): os.mkdir(DIR)DIR = os.path.join(DIR, query.split()[0])if not os.path.exists(DIR): os.mkdir(DIR)###print imagesfor i,(img,Type) in enumerate(ActualImages[:5]): try: req = urllib.request.Request(img, headers={'User-Agent' : header}) raw_img = urllib.request.urlopen(req).read() cntr = len([i for i in os.listdir(DIR) if image_type in i]) + 1 print(cntr)Q1:在行req = urllib.request.Request(img, headers={'User-Agent' : header})Python 會向我顯示一個錯誤,指出預(yù)期的字符串或類似字節(jié)的對象,但如果我刪除了headers={'User-Agent' : header},代碼就可以正常工作。我知道標(biāo)題充當(dāng)許可證,但讓它禁止代碼運(yùn)行很奇怪。有人可以幫助解決這個問題嗎?Q2:根據(jù)幾次測試,我有時會得到HTTP Error 403: Forbidden. 我應(yīng)該更改哪一部分讓 Python 繼續(xù)嘗試,直到我成功下載了 5 次圖像,而不是向我展示它嘗試了 5 次但 1 次下載失?。?
從谷歌圖片中獲取前 5 張圖片
慕田峪9158850
2021-07-04 05:31:40