鱼C论坛

 找回密码
 立即注册
查看: 3563|回复: 12

python教程中OOXX中的问题。

[复制链接]
发表于 2016-7-23 16:38:39 | 显示全部楼层 |阅读模式
20鱼币
def get_page(url):
    html = url_open(url).decode('utf-8')

    a = html.find('current-comment-page')+23         //  教程中讲的偏移23是怎么算的?
    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])    //还有这里的a+9和b+4
        else:
            b = a+9

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

    return img_addrs

帮忙举个例子讲一下偏移,图片如下:

1.jpg
2.jpg

最佳答案

查看完整内容

一.‘current-comment-page[XXXX’正好是23个字符,下一个就是‘]’。中间包含数字(页码) 二: 1.b是“.jpg”,而且.jpg这个字符正好4个字节 2.a是“img src=”,但是取出的网址不能有双引号,故必须加上一个双引号。所以这个字符串正好9字节。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2016-7-23 16:38:40 | 显示全部楼层
一.‘current-comment-page[XXXX’正好是23个字符,下一个就是‘]’。中间包含数字(页码)
二:
1.b是“.jpg”,而且.jpg这个字符正好4个字节
2.a是“img src=”,但是取出的网址不能有双引号,故必须加上一个双引号。所以这个字符串正好9字节。

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2016-7-23 16:56:28 | 显示全部楼层
1、偏移23是怎么算的?
len('current-comment-page">[')
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2016-7-23 17:00:01 | 显示全部楼层
同理:
len('img src="')  #a+9

len('.jpg'')  #b+4
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2016-7-24 02:14:53 | 显示全部楼层
SixPy 发表于 2016-7-23 17:00
同理:
len('img src="')  #a+9

学习了。很有帮助
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2016-7-26 22:08:09 | 显示全部楼层
最幸福是答案是
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2016-7-27 18:54:19 | 显示全部楼层

what's means?
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2016-7-28 18:19:41 | 显示全部楼层
OOXX视频教程里面的代码一运行就是这个结果,求助!!!
Traceback (most recent call last):
  File "D:/Bit德沽/Codgear/Codes/FISHC/download_mm.py", line 67, in <module>
    download_mm()
  File "D:/Bit德沽/Codgear/Codes/FISHC/download_mm.py", line 58, in download_mm
    page_num = int(get_page(url))
  File "D:/Bit德沽/Codgear/Codes/FISHC/download_mm.py", line 22, in get_page
    html = url_open(url).decode('utf-8')
  File "D:/Bit德沽/Codgear/Codes/FISHC/download_mm.py", line 15, in url_open
    response = urllib.request.urlopen(url)
  File "D:\应用软件\python\lib\urllib\request.py", line 162, in urlopen
    return opener.open(url, data, timeout)
  File "D:\应用软件\python\lib\urllib\request.py", line 471, in open
    response = meth(req, response)
  File "D:\应用软件\python\lib\urllib\request.py", line 581, in http_response
    'http', request, response, code, msg, hdrs)
  File "D:\应用软件\python\lib\urllib\request.py", line 503, in error
    result = self._call_chain(*args)
  File "D:\应用软件\python\lib\urllib\request.py", line 443, in _call_chain
    result = func(*args)
  File "D:\应用软件\python\lib\urllib\request.py", line 686, in http_error_302
    return self.parent.open(new, timeout=req.timeout)
  File "D:\应用软件\python\lib\urllib\request.py", line 471, in open
    response = meth(req, response)
  File "D:\应用软件\python\lib\urllib\request.py", line 581, in http_response
    'http', request, response, code, msg, hdrs)
  File "D:\应用软件\python\lib\urllib\request.py", line 509, in error
    return self._call_chain(*args)
  File "D:\应用软件\python\lib\urllib\request.py", line 443, in _call_chain
    result = func(*args)
  File "D:\应用软件\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

Process finished with exit code 1
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2016-7-28 20:48:32 | 显示全部楼层
codgear 发表于 2016-7-28 18:19
OOXX视频教程里面的代码一运行就是这个结果,求助!!!
Traceback (most recent call last):
  File "D: ...

煎蛋网加了反爬虫机制,原来的代码已经不行了,这是我找的其他的,你看看吧:

  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()
复制代码



想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2016-7-29 15:48:29 | 显示全部楼层
浮云骑士 发表于 2016-7-28 20:48
煎蛋网加了反爬虫机制,原来的代码已经不行了,这是我找的其他的,你看看吧:

这个代码是鱼油分享的吧,我也有看到,我就是想测试成功,这个报错跟反爬虫有关??我连续运行的话会报错503,服务器暂时无法服务,我觉得这个错才是因为反爬虫吧。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2016-7-29 16:10:10 From FishC Mobile | 显示全部楼层
我认为完全没必要钻这个牛角尖,又简单方法直接点~
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2016-7-29 17:17:02 | 显示全部楼层
neilyoone 发表于 2016-7-29 16:10
我认为完全没必要钻这个牛角尖,又简单方法直接点~

那倒也是。。因为查到可能是存在编码问题,才跑来请教的
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2016-7-29 20:56:07 | 显示全部楼层
codgear 发表于 2016-7-29 17:17
那倒也是。。因为查到可能是存在编码问题,才跑来请教的

编码应该不会有问题,小甲鱼已经讲的很清楚了,我觉得是我们爬煎蛋网次数太多,所以他们采取了一些措施。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

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

本版积分规则

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

GMT+8, 2024-5-24 16:39

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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