版权声明:本文博主原创,有需要请联系我。 https://blog.csdn.net/myGFZ/article/details/78906961
因为最近在做课程设计,要用python实现网络图片的爬虫,所以特地记录下学到的东西及遇到的坑。
首先,代码来自:
具体如下:
import re
import urllib.request
# ------ 获取网页源代码的方法 ---
def getHtml(url):
page = urllib.request.urlopen(url)
html = page.read()
return html
# ------ getHtml()内输入任意帖子的URL ------
html = getHtml("https://tieba.baidu.com/p/5352556650")
# ------ 修改html对象内的字符编码为UTF-8 ------
html = html.decode('UTF-8')
# ------ 获取帖子内所有图片地址的方法 ------
def getImg(html):
# ------ 利用正则表达式匹配网页内容找到图片地址 ------
reg = r'src="([.*\S]*\.jpg)"'
imgre = re.compile(reg);
imglist = re.findall(imgre, html)
return imglist
imgList = getImg(html)
imgName = 0
for imgPath in imgList:
# ------ 这里最好使用异常处理及多线程编程方式 ------
try:
f = open('D:\\Temp\\'+ str(imgName)+".jpg", 'wb')
f.write((urllib.request.urlopen(imgPath)).read())
print(imgPath)
f.close()
except Exception as e:
print(imgPath+" error")
imgName += 1
print("All Done!")
这是一段很简单的代码,然后只需要把其中的url改成自己想要爬去的网站就可以了。
但是我遇到了一些问题:
urllib.error.URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:777)>
主要的问题就是
SSL: CERTIFICATE_VERIFY_FAILED
所以解决这个问题的方法来自于这里:
https://stackoverflow.com/questions/27835619/urllib-and-ssl-certificate-verify-failed-error
具体做法是在代码中添加这两行:
import ssl
ssl._create_default_https_context = ssl._create_unverified_context
然后问题纠结了,并且顺利实现了网络图片的爬取。