下面程序能夠爬取百度圖片一個網頁里面的所以圖片,值得關注的是匹配字段,正則表達式要寫正確,雖然匹配成功的但是爬取的圖片還是較少,下篇我會采取get方法來請求更多圖片來爬取。
import urllib.request
import re
import time
def open_url(url):
req = urllib.request.Request(url)
req.add_header('User-Agent','Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36 QIHU 360EE')
page = urllib.request.urlopen(req)#打開網頁
html = page.read().decode('utf-8')#網頁解碼
return html
def get_img(html):
p = r'"(https:[^"]+\.jpg)'#匹配的字段
imglist = re.findall(p,html)
#print(html)
for each in imglist:
print(each)
filename = each.split("/")[-1]
urllib.request.urlretrieve(each,filename,None)#保存圖片
#time.sleep(0.01)
if __name__ == '__main__':
#網址
url = 'https://image.baidu.com/search/index?tn=baiduimage&ipn=r&ct=201326592&cl=2&lm=-1&st=-1&fm=result&fr=&sf=1&fmq=1559194736650_R&pv=&ic=&nc=1&z=&hd=&latest=©right=&se=1&showtab=0&fb=0&width=&height=&face=0&istype=2&ie=utf-8&sid=&word=%E5%8A%A8%E6%BC%AB%E5%B0%91%E5%A5%B3'
get_img(open_url(url))
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
