使用python中urllib模块实现简单的图片爬取:
代码1:
import urllib.request
import re
import os
def open_url(url):
req = urllib.request.Request(url)
req.add_header('Referer','http://fanyi.youdao.com/?keyfrom=dict2.top')
req.add_header('User-Agent','Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36')
response = urllib.request.urlopen(req)
html = response.read().decode('utf-8')
return html
def get_img(html):
p = r'<img class="BDE_Image".*?src="([^"]*\.jpg)".*?>'
imglist = re.findall(p,html)
try:
os.mkdir('./pictures')
except FileExistsError:
pass
os.chdir('./pictures')#改变目录到当前文件夹
for img in imglist:
filename = img.split('/')[-1]
urllib.request.urlretrieve(img,filename,None)
if __name__=='__main__':
url = 'http://tieba.baidu.com/p/3823765471'
get_img(open_url(url))
代码2:
import urllib.request