鱼C论坛

 找回密码
 立即注册
查看: 1148|回复: 2

采集豆瓣评价问题 请指教

[复制链接]
发表于 2022-5-1 22:15:09 | 显示全部楼层 |阅读模式

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

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

x
我有个代码采集豆瓣评价

fake useraget 设置了

代理ip也买了

可以是还是采集几页就

这是啥情况 呢请问
下面是代码

请帮我看下,

谢谢

  1. #!/usr/bin/env python
  2. # coding: utf-8

  3. # In[135]:


  4. import json
  5. import random
  6. import time
  7. import copyheaders
  8. import pandas
  9. import requests
  10. from fake_useragent import UserAgent


  11. # In[136]:



  12. #pip install -i https://pypi.doubanio.com/simple/ fake_useragent
  13. import tempfile

  14. a = tempfile.gettempdir()
  15. print(a)
  16. ua = UserAgent(verify_ssl=False)
  17. print(ua.random)


  18. # In[137]:


  19. headers = copyheaders.headers_raw_to_dict(b"""
  20. Accept: application/json
  21. Accept-Language: zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6
  22. Cache-Control: no-cache
  23. Connection: keep-alive
  24. Host: m.douban.com
  25. Pragma: no-cache
  26. Referer: https://m.douban.com/movie/subject/27662747/comments?sort=time&start=25
  27. Sec-Fetch-Dest: empty
  28. Sec-Fetch-Mode: cors
  29. Sec-Fetch-Site: same-origin

  30. User-Agent: ua.random
  31. X-Requested-With: XMLHttpRequest
  32. cookie: bid=wy6mZvf0dsM;ll="118271";
  33. """)


  34. # In[138]:


  35. golols = {
  36.     "dl": {
  37.         'https': '16150'
  38.     }
  39. }


  40. # In[139]:


  41. end_time = time.mktime(time.strptime('2015-01-01 00:00:00','%Y-%m-%d %H:%M:%S'))


  42. # In[140]:


  43. def getrate(text):
  44.     if '很差' in text:
  45.         return '1'
  46.     elif '较差' in text:
  47.         return '2'
  48.     elif '还行' in text:
  49.         return '3'
  50.     elif '推荐' in text:
  51.         return '4'
  52.     elif '力荐' in text:
  53.         return '5'
  54.     else:
  55.         return '-'


  56. # In[141]:


  57. def setproxy():
  58.     try:
  59.         time.sleep(random.randint(1, 10))  
  60.         res = requests.get('http://http.tiqu.alibabaapi.com/getip?num=1&type=2&neek=563834&port=11&lb=1&pb=4&regions=')
  61.         
  62.         ip = (res.json().get("data")[0].get("ip") + ":" + res.json().get("data")[0].get("port"))
  63.         golols['dl']["https"] = "https://" + ip
  64.         print("https://" + ip)
  65.     except Exception as e:
  66.         print(e, "设置代理错误!")
  67.         time.sleep(random.randint(1, 10))
  68.         setproxy()


  69. # In[142]:


  70. def get_proxy(headers):
  71.     #proxy_url为您在网站上的API
  72.     proxy_url = 'http://http.9vps.com/getip.asp?username=17844629386&pwd=4dea396a2a6519e5817632c7552c2d33&geshi=1&fenge=1&fengefu=&getnum=1'
  73.     aaa=requests.get(proxy_url, headers=headers).text
  74.     proxy_host = aaa.splitlines()[0]
  75.     print('代理IP为:'+proxy_host)
  76.     proxy = {
  77.         'http': proxy_host,
  78.         'https': proxy_host,
  79.     }
  80.     return proxy


  81. # In[143]:


  82. def download_start_1(icode, iname):      #改动过
  83.     count = 0   #控制评论start =
  84.     result = []
  85.     pids = []
  86.     for i in range(9999):
  87.         base_api = f'https://m.douban.com/rexxar/api/v2/movie/{icode}/interests?count=50&order_by=latest&anony=0&start={count}&ck=&for_mobile=1'
  88.         print(f'正在请求地址:{base_api}')
  89.         time.sleep(1)
  90.         while True:
  91.             proxy = get_proxy(headers)
  92.             try:
  93.                
  94.    
  95.                 res = requests.get(base_api,headers=headers,proxies=proxy, verify=False,timeout=10)   
  96.                 time.sleep(1)
  97.                 break
  98.             except Exception as e:
  99.                 print(f"网络异常:{e}")
  100.                 get_proxy(headers)
  101.                 time.sleep(5)
  102.         coms_list = res.json().get("interests")   #解析json数据
  103.         print(f'当前页码请求数量',len(coms_list))
  104.         for icom in coms_list:
  105.             if icom.get("id") in pids:
  106.                 print(f"重复id暂不采集: {icom.get('id')}")
  107.                 continue
  108.             else:
  109.                 pids.append(icom.get("id"))
  110.                 count+=1
  111.                 try:
  112.                     saveitem = {}
  113.                     saveitem["pid"] = icom.get("id")
  114.                     saveitem["username"] = icom.get("user").get("id")
  115.                     saveitem["rating_level"] = icom.get("rating").get("value") if icom.get("rating") != None else ''
  116.                     saveitem["create_time"] = icom.get("create_time")
  117.                     saveitem["vote_count"] = icom.get("vote_count")
  118.                     saveitem["comment"] = icom.get("comment")

  119.                     if time.mktime(time.strptime(icom.get("create_time"), '%Y-%m-%d %H:%M:%S')) <= end_time:
  120.                         print(f"超出时间 ==》exit")   
  121.                         data_p = pandas.DataFrame(result)
  122.                         data_p.to_excel(f"C:\\Users\\31051\\Desktop\\wait\\评论\\data_{icode}({iname}).xlsx",index=False)   
  123.                         return
  124.                     result.append(saveitem)
  125.                     print(f'页码:{i} 数量:{count}  {saveitem}')

  126.                 except  Exception as e:

  127.                     print(f"网络异常:{e}")
  128.                     continue

  129.         if len(coms_list) != 0:
  130.             flag_count = 0
  131.         
  132.         if len(coms_list) == 0:
  133.             flag_count = flag_count + 1
  134.         
  135.         if flag_count >= 5:
  136.             print("NO.1")
  137.             print(flag_count)
  138.             break
  139.         
  140.         if  len(coms_list) <=40 and len(coms_list) % 100 != 0:
  141.             print(f"当前页码无数据  exit")
  142.             print("NO.2")
  143.             break

  144.         if count >= res.json().get("total"):
  145.             print(f"超出最大限制 exit")
  146.             print("NO.3")
  147.             break

  148.     print(len(result))
  149.     data_p = pandas.DataFrame(result)
  150. #     data_p.to_excel(f"C:\\Users\\31051\\Desktop\\wait\\评论\\data_{icode}({iname}).xlsx",index=False)


  151. # In[144]:


  152. import pandas as pd


  153. # In[145]:


  154. df_empty = pd.DataFrame(columns = ['name','id'])


  155. # In[146]:


  156. #df_empty = df_empty.append({'name': '一秒钟', 'id': '30257787'}, ignore_index=True)
  157. df_empty = df_empty.append({'name': '寻汉计', 'id': '30464901'}, ignore_index=True)
  158. df_empty = df_empty.append({'name': '日常幻想指南', 'id': '26823520'}, ignore_index=True)
  159. #df_empty = df_empty.append({'name': '寂静之地2', 'id': '30206311'}, ignore_index=True)
  160. #df_empty = df_empty.append({'name': '荞麦疯长', 'id': '30170833'}, ignore_index=True)

  161. #df_empty = df_empty.append({'name': '蜜熊的音乐奇旅', 'id': '26935358'}, ignore_index=True)
  162. #df_empty = df_empty.append({'name': '大红包', 'id': '33457717'}, ignore_index=True)
  163. #df_empty = df_empty.append({'name': '五个扑水的少年', 'id': '35030151'}, ignore_index=True)
  164. #df_empty = df_empty.append({'name': '中国医生', 'id': '35087699'}, ignore_index=True)

  165. #df_empty = df_empty.append({'name': '花木兰', 'id': '26357307'}, ignore_index=True)
  166. #df_empty = df_empty.append({'name': '送你一朵小红花', 'id': '35096844'}, ignore_index=True)

  167. #df_empty = df_empty.append({'name': '宝可梦:超梦的逆袭 进化', 'id': '30272753'}, ignore_index=True)
  168. #df_empty = df_empty.append({'name': '小妇人', 'id': '26348103'}, ignore_index=True)

  169. #df_empty = df_empty.append({'name': '第一次的离别', 'id': '30337172'}, ignore_index=True)
  170. #df_empty = df_empty.append({'name': '哆啦A梦:大雄的新恐龙', 'id': '34454004'}, ignore_index=True)


  171. # In[147]:


  172. df_empty


  173. # In[148]:


  174. for i in range(len(df_empty)):
  175.     flag_count = 0
  176.     icode = df_empty['id'].iloc[i]
  177.     iname = df_empty['name'].iloc[i]

  178.     download_start_1(icode, iname)


  179. # In[ ]:




复制代码




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

使用道具 举报

发表于 2022-5-1 22:34:44 | 显示全部楼层
本帖最后由 isdkz 于 2022-5-1 22:37 编辑

你确定你能爬取几页?

第一:requests 设置 proxy 的时候 url 是要带上协议的,

你提取代理的时候返回的代理只有 ip 地址和端口,所以你的 proxy 字典里面要自己加上去

  1. def get_proxy(headers):
  2.     #proxy_url为您在网站上的API
  3.     proxy_url = 'http://http.9vps.com/getip.asp?username=17844629386&pwd=4dea396a2a6519e5817632c7552c2d33&geshi=1&fenge=1&fengefu=&getnum=1'
  4.     aaa=requests.get(proxy_url, headers=headers).text
  5.     proxy_host = aaa.splitlines()[0]
  6.     print('代理IP为:'+proxy_host)
  7.     proxy = {
  8.         'http': 'http://' + proxy_host,                        # 得在 ip 前面加上协议(代理的类型)
  9.         'https': 'http://' + proxy_host,                       # 得在 ip 前面加上协议(代理的类型)
  10.     }
  11.     return proxy
复制代码


第二:好像你那个代理接口提取出来的代理很多都不能用的

第三:不要随随便便把自己的接口暴露出来
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2022-5-1 22:42:08 | 显示全部楼层
isdkz 发表于 2022-5-1 22:34
你确定你能爬取几页?

第一:requests 设置 proxy 的时候 url 是要带上协议的,

这代码是 买ip的网站给你 实例代码,我没改就,应该没问题吧

采的数据 跟不设置是一样的,都是600条数据
但我一个朋友测试他可以采集1800条
所以我觉得还是被限制了
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

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

本版积分规则

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

GMT+8, 2025-4-29 04:33

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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