用Python爬取某網站的圖片到本地時遇到了問題,請問如何解決?

成功的爬取了網站上所有圖片的鏈接,但當調用download函數下載圖片時出現一個問題,瀏覽器能夠打開圖片鏈接,請問怎麼解決? (windos系統 Python2.7)

#-*- coding:utf-8 -*-
import requests
from bs4 import BeautifulSoup
headers={
"User-Agent":"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36"
}
#爬取網頁,獲得所有圖片鏈接的列表
def get_imgs(page):
html=requests.get(page,headers=headers)
soup=BeautifulSoup(html.text,"lxml")
imgs=soup.select("a.js-entry-detail-link &> img")
img_links=[img.get("src") for img in imgs]
return img_links
#下載圖片
def download(img_link):
html=requests.get(img_link,headers=headers)
img=img_link.split("/")[-2]
with open("./taylorSwift/img"+".jpg","wb") as f:
f.write(html.content)
print "download "+img+"..."
def main():
page="http://weheartit.com/inspirations/taylorswift? scrolling=truepage=1before=256538431"
img_links=get_imgs(page)
for link in img_links:
download(link)
main()
#download("http://data.whicdn.com/images/208856283/superthumb.jpg") 想直接訪問圖片鏈接,結果引發同樣錯誤


謝邀。作為知乎首次被邀請。還是很高興的。

你用的是request這個模塊他的官方手冊里是快速上手 — Requests 2.10.0 文檔

成為大神之路就是官方文檔+google

然後其中你要保留的圖片的二進位顯示是這個r.content

我演示一下:

比如抓取https://www.urlteam.org/wp-content/uploads/2015/08/14110321028932-e1440584371928.jpg

import requests
r = requests.get("https://www.urlteam.org/wp-content/uploads/2015/08/14110321028932-e1440584371928.jpg")
f = open("1.jpg","wb")
f.write(r.content)
f.close()

然後就在當前目錄下可以看到這個圖了,我自己試了一下,確定可以,我電腦環境是linux 16.04 python版本是2.7。

如果你在這部分模塊測試沒問題。那麼問題就比較可能出現在因為符號可能是中文下的,。或者一些細節問題。得再調試。


報錯信息寫很清楚,19行代碼有問題。

怎麼解決

1、在download函數內的第一行加一個print img_link

2、將輸出值貼到瀏覽器看一下。

下次問問題,只貼圖片,不貼源代碼文本,得到回答的機會就減少。


加個代理:

+proxy = {"http": "http://176.31.96.198:3128"}
+html = requests.get(img_link, headers=headers, proxies=proxy)
—html=requests.get(img_link,headers=headers)


首先看請求到了圖片的地址沒有,然後看寫入到本地是否有問題,試試urlretrieve


推薦閱讀:

python 爬蟲 圖片抓取問題,有的網站中的圖片不能抓取?
千里挑一的我乎妹子大V排行榜(數據初探1)
Python中那些神一樣的代碼
Python3.6正式版要來了,你期待哪些新特性?
神奇的yield

TAG:Python | 網頁爬蟲 |