鱼C论坛

 找回密码
 立即注册
查看: 4479|回复: 9

零基础学习Python第56:OOXX

[复制链接]
发表于 2016-7-22 12:00:37 | 显示全部楼层 |阅读模式
20鱼币
import urllib.request
import os
import random


def url_open(url):
    req = urllib.request.Request(url)
    req.add_header('User-Agent','Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.154 Safari/537.36 LBBROWSER')

    proxies = ['36.7.172.18:82','42.96.195.147:82','106.75.128.89:80']
    proxy = random.choice(proxies)

    proxy_support = urllib.request.ProxyHandler({'http':proxy})
    opener = urllib.request.build_opener(proxy_support)
    urllib.request.install_opener(opener)


    response = urllib.request.urlopen(url)
    html = response.read()

    return html

def get_page(url):
    html = url_open(url).decode('utf-8')

    a = html.find('current-comment-page')
    b = html.find(']',a)

    return html[a:b]


def find_imgs(url):
    html = url_open(url).decode('utf-8')
    img_addrs = []

    a = html.find('img src=')

    while a != -1:

        b = html.find('.jpg',a,a+255)
        if b!= -1:
            img_addrs.append(html[a+9:b+4])
        else:
            b = a+9

        a = html.find('img src=',b)

    return img_addrs




def save_imgs(folder,img_addrs):
    for each in img_addrs:
        filename = each.spilt('/')[-1]
        with open(filename, 'wb') as f:
            img = url_open(each)
            f.write(img)

def download_mm(folder = 'OOXX',pages = 10):
    os.mkdir(folder)
    os.chdir(folder)

    url = "http://jandan.net/ooxx/"
    page_num = int(get_page(url))

    for i in range(pages):
        page_num -= i
        page_url = url + 'page-' + str(page_num) + '#comments'
        img_addrs = find_imgs(page_url)
        save_imgs(folder,img_addrs)

if __name__ == '__main__':
    download_mm()
出现错误
Traceback (most recent call last):
  File "C:\Users\lihongfei\Desktop\download_mm.py", line 74, in <module>
    download_mm()
  File "C:\Users\lihongfei\Desktop\download_mm.py", line 65, in download_mm
    page_num = int(get_page(url))
  File "C:\Users\lihongfei\Desktop\download_mm.py", line 24, in get_page
    html = url_open(url).decode('utf-8')
  File "C:\Users\lihongfei\Desktop\download_mm.py", line 18, in url_open
    response = urllib.request.urlopen(url)
  File "F:\python\lib\urllib\request.py", line 162, in urlopen
    return opener.open(url, data, timeout)
  File "F:\python\lib\urllib\request.py", line 471, in open
    response = meth(req, response)
  File "F:\python\lib\urllib\request.py", line 581, in http_response
    'http', request, response, code, msg, hdrs)
  File "F:\python\lib\urllib\request.py", line 503, in error
    result = self._call_chain(*args)
  File "F:\python\lib\urllib\request.py", line 443, in _call_chain
    result = func(*args)
  File "F:\python\lib\urllib\request.py", line 686, in http_error_302
    return self.parent.open(new, timeout=req.timeout)
  File "F:\python\lib\urllib\request.py", line 471, in open
    response = meth(req, response)
  File "F:\python\lib\urllib\request.py", line 581, in http_response
    'http', request, response, code, msg, hdrs)
  File "F:\python\lib\urllib\request.py", line 509, in error
    return self._call_chain(*args)
  File "F:\python\lib\urllib\request.py", line 443, in _call_chain
    result = func(*args)
  File "F:\python\lib\urllib\request.py", line 589, in http_error_default
    raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 503: Service Temporarily Unavailable

怎么办?

最佳答案

查看完整内容

善用【论坛搜索】功能,那里可能有您想要的答案! 论坛里讨论n遍了~~~~~~~~
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2016-7-22 12:00:38 | 显示全部楼层
善用【论坛搜索】功能,那里可能有您想要的答案!

论坛里讨论n遍了~~~~~~~~
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2016-7-22 13:27:24 | 显示全部楼层
SixPy 发表于 2016-7-22 12:02
善用【论坛搜索】功能,那里可能有您想要的答案!

论坛里讨论n遍了~~~~~~~~

是吗?我看看
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2016-7-22 13:41:46 | 显示全部楼层
SixPy 发表于 2016-7-22 12:02
善用【论坛搜索】功能,那里可能有您想要的答案!

论坛里讨论n遍了~~~~~~~~

好吧,好像是啊,我没注意。
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2016-7-22 14:48:26 | 显示全部楼层
SixPy 发表于 2016-7-22 12:02
善用【论坛搜索】功能,那里可能有您想要的答案!

论坛里讨论n遍了~~~~~~~~

找到答案了。
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2016-7-26 00:03:41 | 显示全部楼层

我也遇到相同情况,能帮忙解决一下吗?
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2016-7-26 08:29:08 | 显示全部楼层
frezs 发表于 2016-7-26 00:03
我也遇到相同情况,能帮忙解决一下吗?

他们说简单网煎蛋网加了反爬虫机制,这是我在帖子里找到的能用的代码:
希望对你有用:

  1. import urllib.request
  2. import urllib.error
  3. import os
  4. import sys
  5. import http.server
  6. import http.client
  7. import time
  8. import re
  9. import random
  10. import math

  11. data = None
  12. headers = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36'}
  13. enctype = 'utf-8'
  14. proxies = []
  15. max_error_times = 5        #最多允许失败5次,否则放弃该图片下载

  16. def create_localhost():
  17.     number = int((math.sqrt(5)-1)/2) * len(proxies)
  18.     for x in range(number):
  19.         proxies.append(None)

  20. def get_result(req_or_url,is_retrieve=False,filename = None):         #flag是否使用retrieve
  21.     error_time = 0
  22.     while True:
  23.         try:
  24.             if error_time == max_error_times:
  25.                 print('失败次数达%d次......放弃操作' % max_error_times)
  26.                 return None
  27.             error_time += 1
  28.             if is_retrieve:
  29.                 return urllib.request.urlretrieve(req_or_url,filename)
  30.             else:
  31.                 return urllib.request.urlopen(req_or_url)
  32.         except urllib.error.URLError as e:
  33.             if hasattr(e,'code'):         
  34.                 print(e.code,e.reason)
  35.                 change_proxy()
  36.                 continue
  37.             elif hasattr(e,'reason'):
  38.                 print(e)
  39.                 change_proxy()
  40.                 continue
  41.         except (ConnectionResetError,http.client.BadStatusLine) as e:
  42.             print(e)
  43.             change_proxy()
  44.             continue
  45.         except TimeoutError as e:
  46.             print(e)
  47.             print('服务器长时间无响应,自动切换代理.....')
  48.             change_proxy()
  49.             continue

  50. def get_proxy():
  51.     global data,headers,proxies
  52.     req = urllib.request.Request('http://www.xici.net.co',None,headers)
  53.     response = get_result(req)
  54.     html = response.read().decode('utf-8')
  55.     p = re.compile(r'''<tr\sclass[^>]*>\s+
  56.                                     <td>.+</td>\s+
  57.                                     <td>(.*)?</td>\s+
  58.                                     <td>(.*)?</td>\s+
  59.                                     <td>(.*)?</td>\s+
  60.                                     <td>(.*)?</td>\s+
  61.                                     <td>(.*)?</td>\s+
  62.                                     <td>(.*)?</td>\s+
  63.                                 </tr>''',re.VERBOSE)
  64.     proxy_list = p.findall(html)
  65.     for each_proxy in proxy_list[1:]:
  66.         if each_proxy[4] == 'HTTP':
  67.             proxies.append(each_proxy[0]+':'+each_proxy[1])

  68. def change_proxy():
  69.     proxy = random.choice(proxies)
  70.     if proxy == None:
  71.         proxy_support = proxy_support = urllib.request.ProxyHandler({})
  72.     else:
  73.         proxy_support = urllib.request.ProxyHandler({'http':proxy})
  74.     opener = urllib.request.build_opener(proxy_support)
  75.     opener.addheaders = [('User-Agent',headers['User-Agent'])]
  76.     urllib.request.install_opener(opener)
  77.     print('智能切换代理:%s' % ('本机' if proxy==None else proxy))

  78. def get_page():         #获取最大页数
  79.     home = 'http://jandan.net/ooxx'
  80.     global data,headers,enctype
  81.     req = urllib.request.Request(home,data,headers)
  82.     response = get_result(req)
  83.     html = response.read().decode(enctype)
  84.     find_string = 'current-comment-page'
  85.     find_start = html.index(find_string) + len(find_string) + 3
  86.     find_end = html.index(']',find_start+1)
  87.     return int(html[find_start:find_end])
  88. test = None
  89. def get_pic(page):      #生成器,返回一个图片链接
  90.     global data,headers,enctype
  91.     while True:
  92.         url = 'http://jandan.net/ooxx/page-%d' % page
  93.         print('当前页面:%d' % page)
  94.         req = urllib.request.Request(url,data,headers)
  95.         response = get_result(req)
  96.         if response == None:
  97.             print('获取页面失败.....')
  98.             sys.exit()
  99.         html = response.read().decode(enctype)
  100.         pic = re.compile(r'<img\s+src="(http://.+?\.(?:jpg|jpeg|gif))"')
  101.         for pic in pic.finditer(html):
  102.             yield pic.group(1)
  103.         time.sleep(5)
  104.         page -= 1
  105.         if page<1:
  106.             break

  107. save_path = 'G:\\图片\\妹子图'

  108. def download():
  109.     count = 1
  110.     global data,headers
  111.     for pic_url in get_pic(get_page()):         #get_page()改为页数如1000可从1000页开始下载
  112.         file_name = os.path.split(pic_url)[1]
  113.         if not os.path.isdir(save_path):    #目录不存在就创建
  114.             os.makedirs(save_path)
  115.         get_result(pic_url,True,save_path+'\\'+file_name)
  116.         print('本次成功下载第%d个图片! %s' % (count , pic_url))
  117.         count += 1

  118. if __name__ == '__main__':
  119.     get_proxy()
  120.     create_localhost()
  121.     download()
复制代码



小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2016-8-1 16:25:40 | 显示全部楼层
............
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2016-8-1 16:26:26 | 显示全部楼层
.............................df
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2016-8-1 16:41:52 | 显示全部楼层
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2026-2-21 20:39

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表