Advertisement
rs6000

crawler_DIA_simple

Jan 14th, 2018
235
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.10 KB | None | 0 0
  1. # coding: utf-8
  2.  
  3. # 開始動工
  4. '''
  5. 2018/01/15
  6. 預計改成class寫法....
  7.  
  8. 2018/01/14
  9. 可批次寫入資料庫,程式大致完成
  10. 2018/01/13
  11. 解決sql插入問題
  12. 2018/01/08
  13. 重新啟動專案
  14. 2017/10/25
  15. '''
  16. import requests
  17. from bs4 import BeautifulSoup
  18. import sqlite3 as lite
  19. import os,time, shutil, dataset
  20.  
  21. #取得當前工作路徑加存檔路徑
  22. workpath=os.getcwd()+'\crawler_DIA'
  23.  
  24. #如果目錄不存在就建立該目錄
  25. if not os.path.isdir(workpath):
  26.     os.makedirs(workpath)
  27.  
  28. #在爬蟲程式開始運作前,先建立資料庫
  29. #資料庫設定
  30. database='dia.sqlite'
  31. savetodb=os.path.join(workpath,database)
  32.  
  33. '''
  34. #20180113 sqlite連線時會自動建立所以下面程式碼可以省略
  35. #如果檔案不存在就建立該檔案
  36. if not os.path.isfile(os.path.join(workpath,database)):
  37.    makefile=open(os.path.join(workpath,database),'w')
  38.    makefile.close()
  39. '''
  40.  
  41. #建立資料表的SQL
  42. sql1="""CREATE TABLE IF NOT EXISTS 'profile'
  43. ('id' INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL ,\
  44. 'name' VARCHAR NOT NULL ,'profile_pic' TEXT NOT NULL \
  45. DEFAULT (null) ,'age' INTEGER NOT NULL ,\
  46. 'gender' VARCHAR NOT NULL ,'appearance' TEXT,\
  47. 'occupation' VARCHAR,'education' VARCHAR,\
  48. 'religion' VARCHAR,'relationship_status' VARCHAR,\
  49. 'has_children' VARCHAR,'wants_children' VARCHAR,\
  50. 'willing_to_relocate' VARCHAR,'smoking' VARCHAR,\
  51. 'drinking' VARCHAR)"""
  52.  
  53. #資料庫欄位的初始值,id值要用None
  54. dict={'id':None,
  55. 'profile_pic':'NA',
  56. 'age':'NA',
  57. 'gender':'NA',
  58. 'appearance':'NA',
  59. 'occupation':'NA',
  60. 'education':'NA',
  61. 'religion':'NA',
  62. 'relationship_status':'NA',
  63. 'has_children':'NA',
  64. 'wants_children':'NA',
  65. 'willing_to_relocate':'NA',
  66. 'smoking':'NA',
  67. 'drinking':'NA'}
  68.  
  69. #資料庫連線,如果路徑底下沒有dia.sqlite則會自動建立
  70. conn= lite.connect(savetodb)
  71. cur=conn.cursor()
  72.  
  73. #執行SQL
  74. cur.execute(sql1)
  75. #commit&close
  76. conn.commit()
  77. conn.close()
  78.  
  79. #目標網址
  80. base_url='https://www.dateinasia.com'
  81.  
  82. #篩選條件
  83. #philippines cebu ,女 18-30歲 ,sorted by last active 差別在s=?
  84. #searchfor='&g=2&af=18&at=30&c=PH&ci=Cebu&s=2'
  85. #philippines cebu ,女 18-30歲 ,sorted by newest members
  86. searchfor='&g=2&af=18&at=30&c=PH&ci=Cebu&s=3'
  87.  
  88. #頁數
  89. page_list=[]
  90. #頁面的使用者連結
  91.  
  92. #起始的頁數
  93. pg=0
  94.  
  95. #要抓的頁數(+1)
  96. num=4
  97.  
  98. for i in range(0,num+1):
  99.     get_page='pg='+str(pg)
  100.     pg+=1
  101.     page_list.append(base_url+'/Search.aspx?'+get_page+searchfor)
  102.  
  103. #測試
  104. #print(len(page_list),page_list)
  105.  
  106. #使用者profile的頁面連結
  107. User_Page_Link=[]
  108. #記錄出錯的頁面Link
  109. error_page=[]
  110.  
  111. #取得每個頁面中的使用者的連結(一頁會有60個使用者)
  112. for get_user_link in page_list:
  113.     #print(get_user_link)
  114.     res=requests.get(get_user_link)
  115.     soup=BeautifulSoup(res.content, 'html5lib')
  116.     try:
  117.         get_data=soup.find_all("span",{'class':'responsive-container galleryphoto-responsive'})
  118.         for link in get_data:
  119.             UserName=link.find('img').attrs['alt'].replace(' ','+')
  120.             UserLink=base_url+'/'+UserName
  121.             User_Page_Link.append(UserLink)
  122.             #
  123.             #print(UserName)
  124.             #print(UserLink)
  125.     except:
  126.         print('error: {}'.format(get_user_link))
  127.         error_page.append(get_user_link)
  128.         pass
  129. #測試
  130. #print('User_Page_Link=',str(len(User_Page_Link)),User_Page_Link)
  131.  
  132. #記錄個人頁面抓取時出錯的訊息
  133. error_profile=[]
  134. #建立資料庫連線
  135. con=lite.connect(savetodb)
  136. cur=con.cursor()
  137.  
  138. #記錄程式執行時間
  139. time_start=time.time()
  140.  
  141. for get_profile in User_Page_Link:
  142.    
  143.     page_html=requests.get(get_profile)
  144.     page_soup=BeautifulSoup(page_html.text,'lxml')
  145.  
  146.     try:
  147.         #使用者的ID與大頭照
  148.         user=page_soup.select('.responsive-image-local')
  149.         #用chrome info lite選取標籤 快
  150.         #select css的用法
  151.         #注意這邊用select的用法,跟前面用find的差異
  152.         for i in user:
  153.             username=i['alt']
  154.             userpic=i['src']
  155.  
  156.         dict.update({'name':username})
  157.         dict.update({'profile_pic':userpic})
  158.  
  159.         #使用者的個人資料
  160.         get_info= page_soup.find_all('dt')
  161.        
  162.         for i in get_info:
  163.             try:
  164.                 key=i.text.replace(':','').replace(' ','_').lower()
  165.                 value=i.next_sibling.text
  166.                 dict.update({key:value})
  167.  
  168.             except:
  169.                 pass
  170.            
  171.     except:
  172.             print('error: {}'.format(get_profile))
  173.             error_profile.append(get_profile)
  174.             pass
  175.    
  176.     #寫入資料庫
  177.     cur.execute("INSERT or ignore INTO profile VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",[dict["id"],dict["name"],dict["profile_pic"],dict["age"],dict["gender"],dict["appearance"],dict["occupation"],dict["education"],dict["religion"],dict["relationship_status"],dict["has_children"],dict["wants_children"],dict["willing_to_relocate"],dict["smoking"],dict["drinking"]])
  178.     con.commit()
  179.     #抓完一筆休息3秒
  180.     time.sleep(3)
  181.  
  182. #關閉資料庫連線
  183. con.close()
  184.  
  185. time_end=time.time()
  186. #印出程式執行時間
  187. print(time_end-time_start)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement