您的位置:首页技术文章
文章详情页

网页爬虫 - python爬虫爬图,报错<urlopen error no hsot given>.

【字号: 日期:2022-09-02 18:51:20浏览:33作者:猪猪

问题描述

python利用urllib爬虫,图片获取二十几张后就报错python版本3.6 windows系统下运行

urllib.error.URLError:<urlopen error no host given>

代码如下:

#!/usr/bin/python# -*- coding:utf-8 -*-import urllibimport requestsimport refrom bs4 import BeautifulSoupimport csvimport socket socket.setdefaulttimeout(300)headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36'}#url池url1 = (’http://jandan.net/ooxx/page-’)urls = []src_list = []for i in range(2000,2020):urls.append(url1+str(i))print (urls) for url in urls:#从url池中获取url r = requests.get(url,headers = headers)#获取页面 html = BeautifulSoup(r.text,’html.parser’)#利用tag结构划分#获取名称 for link in html.find_all(’img’):src_list.append(’http:’+link.get(’src’))src_list.pop()print (src_list)tmp = 1for src in src_list: urllib.request.urlretrieve(src,r’C:Users姜梦天Desktopspiderimg%s.jpg’ % tmp) tmp += 1 print (’下载完毕’).....尝试解决未果...求各位大大DEBUG....

问题解答

回答1:

#coding=utf-8import osimport requestsfrom pyquery import PyQuery as Qdef download_image(image_url): if not image_url.startswith(’http:’):image_url = ’http:{}’.format(image_url) image_dir = ’./image’ if not os.path.exists(image_dir):os.mkdir(image_dir) _, image_name = os.path.split(image_url) image_path = os.path.join(image_dir, image_name) print ’download:’, image_url, try:r = requests.get(image_url)with open(image_path, ’wb’) as f: f.write(r.content)print ’success’ except:print ’error’if __name__ == ’__main__’: for i in range(2000, 2020):url = ’http://jandan.net/ooxx/page-{0}’.format(i)print ’get:’, urlr = requests.get(url)for _ in Q(r.text).find(’img’): image_url = Q(_).attr(’src’) download_image(image_url)回答2:

......改进了代码.写入了try.虽然还是会报错......但是不妨碍继续下载图片........代码如下:

#!/usr/bin/python# -*- coding:utf-8 -*-import urllibimport requestsimport refrom bs4 import BeautifulSoupimport csvimport socket socket.setdefaulttimeout(300)headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36'}#url池url1 = (’http://jandan.net/ooxx/page-’)urls = []src_list = []for i in range(1500,2380):urls.append(url1+str(i))print (urls) for url in urls:#从url池中获取url r = requests.get(url,headers = headers)#获取页面 html = BeautifulSoup(r.text,’html.parser’) for link in html.find_all(’img’):try: src_list.append(’http:’+link.get(’src’))except: print (’url获取错误’) src_list.pop()print (src_list)tmp = 0for src in src_list: try:urllib.request.urlretrieve(src,r’C:Users姜梦天Desktopspiderimg%s.jpg’ % tmp)tmp = tmp+1 except:print (’失败’) print (’下载完毕’)

可以下载众多妹子的图片了

标签: Python 编程