鱼C论坛

 找回密码
 立即注册
查看: 1832|回复: 3

[已解决]爬虫输出问题

[复制链接]
发表于 2020-3-18 21:25:08 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
  1. from urllib.parse import urlencode
  2. import requests
  3. import os
  4. from multiprocessing import Pool
  5. import time


  6. base_url = 'https://www.toutiao.com/api/search/content/?'
  7. headers = {
  8.     'Referer':'https://www.toutiao.com/search/?keyword=%E5%9B%BE%E7%89%87',
  9.     'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.132 Safari/537.36',
  10.     'X-Requested-With':'XMLHttpRequest'
  11. }


  12. def get_page(offset):
  13.     params = {
  14.         'aid': 24,
  15.         'app_name': 'web_search',
  16.         'offset': offset,
  17.         'format': 'json',
  18.         'keyword': '街拍',
  19.         'count': 20,
  20.         'en_qc': 1,
  21.         'cur_tab': 1,
  22.         'from': 'search_tab',
  23.         'pd': 'synthesis',
  24.         'timestamp': '1584520318379'
  25.     }
  26.     url = base_url + urlencode(params)
  27.     try:
  28.         response = requests.get(url, headers=headers)
  29.         response.raise_for_status()
  30.         response.encoding = response.apparent_encoding
  31.         return response.json()
  32.     except requests.ConnectionError as e:
  33.         print('Error', e.args)


  34. def get_images(json):
  35.     if json.get('data'):
  36.         for item in json.get('data'):
  37.             title = item.get('title')
  38.             images = item.get('image_list')
  39.             for image in images:
  40.                 yield {
  41.                     'image':image.get('url'),
  42.                     'title':title
  43.                 }


  44. def save_image(item):
  45.     if not os.path.exists(item.get('title')):
  46.         os.mkdir(item.get('title'))
  47.     try:
  48.         response = requests.get(item.get('image'))
  49.         if response.status_code == 200:
  50.             file_path = '{0}/{1}.{2}'.format(item.get('title'), time.time(), 'jpg')
  51.             if not os.path.exists(file_path):
  52.                 with open(file_path, 'wb', encoding='utf8') as f:
  53.                     f.write(response.content)
  54.             else:
  55.                 print('已经存在', file_path)
  56.     except requests.ConnectionError:
  57.         print('下载不成功')


  58. def main(offset):
  59.     json = get_page(offset)
  60.     for item in get_images(json):
  61.         print(item)
  62.         save_image(item)


  63. GROUP_START = 1
  64. GROUP_END = 10


  65. if __name__ == '__main__':
  66.     pool = Pool()
  67.     groups = ([x * 20 for x in range(GROUP_START, GROUP_END + 1)])
  68.     pool.map(main, groups)
  69.     pool.close()
复制代码


麻烦请教大神,我在爬头条图片时,代码成功完成了,但是并没有输出任何东西,值显示    Process finished with exit code 0
网上查了后还是解决不了,是python解释器设置问题么?还是其他
最佳答案
2020-3-18 21:31:38
。。。
二进制写入数据还有encoding???
  1. from urllib.parse import urlencode
  2. import requests
  3. import os
  4. from multiprocessing import Pool
  5. import time


  6. base_url = 'https://www.toutiao.com/api/search/content/?'
  7. headers = {
  8.     'Referer':'https://www.toutiao.com/search/?keyword=%E5%9B%BE%E7%89%87',
  9.     'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.132 Safari/537.36',
  10.     'X-Requested-With':'XMLHttpRequest'
  11. }


  12. def get_page(offset):
  13.     params = {
  14.         'aid': 24,
  15.         'app_name': 'web_search',
  16.         'offset': offset,
  17.         'format': 'json',
  18.         'keyword': '街拍',
  19.         'count': 20,
  20.         'en_qc': 1,
  21.         'cur_tab': 1,
  22.         'from': 'search_tab',
  23.         'pd': 'synthesis',
  24.         'timestamp': '1584520318379'
  25.     }
  26.     url = base_url + urlencode(params)
  27.     try:
  28.         response = requests.get(url, headers=headers)
  29.         response.raise_for_status()
  30.         response.encoding = response.apparent_encoding
  31.         return response.json()
  32.     except requests.ConnectionError as e:
  33.         print('Error', e.args)


  34. def get_images(json):
  35.     if json.get('data'):
  36.         for item in json.get('data'):
  37.             title = item.get('title')
  38.             images = item.get('image_list')
  39.             for image in images:
  40.                 yield {
  41.                     'image':image.get('url'),
  42.                     'title':title
  43.                 }


  44. def save_image(item):
  45.     if not os.path.exists(item.get('title')):
  46.         os.mkdir(item.get('title'))
  47.     try:
  48.         response = requests.get(item.get('image'))
  49.         if response.status_code == 200:
  50.             file_path = '{0}/{1}.{2}'.format(item.get('title'), time.time(), 'jpg')
  51.             if not os.path.exists(file_path):
  52.                 with open(file_path, 'wb') as f:
  53.                     f.write(response.content)
  54.             else:
  55.                 print('已经存在', file_path)
  56.     except requests.ConnectionError:
  57.         print('下载不成功')


  58. def main(offset):
  59.     json = get_page(offset)
  60.     for item in get_images(json):
  61.         print(item)
  62.         save_image(item)


  63. GROUP_START = 1
  64. GROUP_END = 10


  65. if __name__ == '__main__':
  66.     pool = Pool()
  67.     groups = ([x * 20 for x in range(GROUP_START, GROUP_END + 1)])
  68.     pool.map(main, groups)
  69.     pool.close()
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2020-3-18 21:31:38 | 显示全部楼层    本楼为最佳答案   
。。。
二进制写入数据还有encoding???
  1. from urllib.parse import urlencode
  2. import requests
  3. import os
  4. from multiprocessing import Pool
  5. import time


  6. base_url = 'https://www.toutiao.com/api/search/content/?'
  7. headers = {
  8.     'Referer':'https://www.toutiao.com/search/?keyword=%E5%9B%BE%E7%89%87',
  9.     'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.132 Safari/537.36',
  10.     'X-Requested-With':'XMLHttpRequest'
  11. }


  12. def get_page(offset):
  13.     params = {
  14.         'aid': 24,
  15.         'app_name': 'web_search',
  16.         'offset': offset,
  17.         'format': 'json',
  18.         'keyword': '街拍',
  19.         'count': 20,
  20.         'en_qc': 1,
  21.         'cur_tab': 1,
  22.         'from': 'search_tab',
  23.         'pd': 'synthesis',
  24.         'timestamp': '1584520318379'
  25.     }
  26.     url = base_url + urlencode(params)
  27.     try:
  28.         response = requests.get(url, headers=headers)
  29.         response.raise_for_status()
  30.         response.encoding = response.apparent_encoding
  31.         return response.json()
  32.     except requests.ConnectionError as e:
  33.         print('Error', e.args)


  34. def get_images(json):
  35.     if json.get('data'):
  36.         for item in json.get('data'):
  37.             title = item.get('title')
  38.             images = item.get('image_list')
  39.             for image in images:
  40.                 yield {
  41.                     'image':image.get('url'),
  42.                     'title':title
  43.                 }


  44. def save_image(item):
  45.     if not os.path.exists(item.get('title')):
  46.         os.mkdir(item.get('title'))
  47.     try:
  48.         response = requests.get(item.get('image'))
  49.         if response.status_code == 200:
  50.             file_path = '{0}/{1}.{2}'.format(item.get('title'), time.time(), 'jpg')
  51.             if not os.path.exists(file_path):
  52.                 with open(file_path, 'wb') as f:
  53.                     f.write(response.content)
  54.             else:
  55.                 print('已经存在', file_path)
  56.     except requests.ConnectionError:
  57.         print('下载不成功')


  58. def main(offset):
  59.     json = get_page(offset)
  60.     for item in get_images(json):
  61.         print(item)
  62.         save_image(item)


  63. GROUP_START = 1
  64. GROUP_END = 10


  65. if __name__ == '__main__':
  66.     pool = Pool()
  67.     groups = ([x * 20 for x in range(GROUP_START, GROUP_END + 1)])
  68.     pool.map(main, groups)
  69.     pool.close()
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2020-3-18 21:33:09 | 显示全部楼层
qiuyouzhi 发表于 2020-3-18 21:31
。。。
二进制写入数据还有encoding???

改了之后还是不行。。。
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2020-3-19 11:10:04 | 显示全部楼层
  1. from urllib.parse import urlencode
  2. import requests
  3. import os
  4. import time
  5. from multiprocessing import Pool
  6. from hashlib import md5



  7. base_url = 'https://www.toutiao.com/api/search/content/?'
  8. headers = {
  9.     'Referer': 'https://www.toutiao.com/search/?keyword=%E5%9B%BE%E7%89%87',
  10.     'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.132 Safari/537.36',
  11.     'X-Requested-With': 'XMLHttpRequest',
  12.     'Cookie': 'tt_webid=6804026100667581959; WEATHER_CITY=%E5%8C%97%E4%BA%AC; tt_webid=6804026100667581959; csrftoken=bd43b1b47601e4d2a2e1e143418d047a; ttcid=b334bc3935ae486cacecaeb90c43c7bd27; SLARDAR_WEB_ID=6be7deee-3b7e-4fc3-b933-80b9ef3e934a; s_v_web_id=verify_k7y17xvx_JXDn3y0R_pd7H_47Ow_9dG3_yShA8wX7QWCz; __tasessionId=p53vp50rz1584578659164; tt_scid=ElNCkMU3P.LmI.6-x09lMgCsRockEtxdx5a50beaePY7m3r7ne9z4Rz7.YeDofWY1e89'
  13. }


  14. def get_page(offset):
  15.     timestamp = int(time.time())
  16.     params = {
  17.         'aid': 24,
  18.         'app_name': 'web_search',
  19.         'offset': offset,
  20.         'format': 'json',
  21.         'autoload':'true',
  22.         'keyword': '街拍',
  23.         'count': 20,
  24.         'en_qc': 1,
  25.         'cur_tab': 1,
  26.         'from': 'search_tab',
  27.         'pd': 'synthesis',
  28.         'timestamp': timestamp
  29.     }
  30.     url = base_url + urlencode(params)
  31.     try:
  32.         response = requests.get(url, headers=headers)
  33.         if response.status_code == 200:
  34.             response.encoding = response.apparent_encoding
  35.             return response.json()
  36.         return None
  37.     except requests.ConnectionError as e:
  38.         print('Error', e.args)
  39.         return None


  40. def get_images(html):
  41.     if html.get('data'):
  42.         html = html.get('data')
  43.         for item in html:
  44.             if item.get('title'):
  45.                 title = item.get('title').replace(' |', ' ').replace('\\', ' ')
  46.             if item.get('image_list'):
  47.                 for image_urls in item.get('image_list'):
  48.                     image_url = image_urls['url']
  49.                     yield {
  50.                         'title': title,
  51.                         'image': image_url
  52.                     }
  53.     else:
  54.         print('没有获取到数据')


  55. def save_image(item):
  56.     img_path = 'images' + '/' + item.get('title')
  57.     if not os.path.exists(img_path):
  58.         try:
  59.             os.mkdir(img_path)
  60.         except OSError:
  61.             print('文件命名错误')
  62.     try:
  63.         response = requests.get(item.get('image'))
  64.         if response.status_code == 200:
  65.             file_path = '{0}/{1}.{2}'.format(img_path, md5(response.content).hexdigest(), 'jpg')
  66.             if not os.path.exists(file_path):
  67.                 with open(file_path, 'wb') as f:
  68.                     f.write(response.content)
  69.             else:
  70.                 print('已经存在', file_path)
  71.     except requests.ConnectionError:
  72.         print('下载不成功')
  73.     except OSError:
  74.         print('图片名称格式不对')


  75. def main(offset):
  76.     html = get_page(offset)
  77.     for item in get_images(html):
  78.         print(item)
  79.         save_image(item)


  80. GROUP_START = 0
  81. GROUP_END = 10


  82. if __name__ == '__main__':
  83.     pool = Pool()
  84.     group = ([x * 20 for x in range(GROUP_START, GROUP_END + 1)])
  85.     pool.map(main, group)
  86.     pool.close()
  87.     pool.join()
复制代码


已经解决了
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

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

本版积分规则

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

GMT+8, 2025-6-9 06:24

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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