经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 程序设计 » Python » 查看文章
Python爬虫爬取ECVA论文标题作者摘要关键字等信息并存储到mysql数据库
来源:cnblogs  作者:杨传伟  时间:2021/6/15 9:18:25  对本文有异议

网站截图:

 

 

 

 源代码:

  1. 1 import re
  2. 2 import requests
  3. 3 import pymysql
  4. 4 from bs4 import BeautifulSoup
  5. 5 import lxml
  6. 6 import traceback
  7. 7 import time
  8. 8 import json
  9. 9 from lxml import etree
  10. 10 def query(sql,*args):
  11. 11 """
  12. 12 封装通用查询
  13. 13 :param sql:
  14. 14 :param args:
  15. 15 :return: 返回查询结果以((),(),)形式
  16. 16 """
  17. 17 conn,cursor = get_conn();
  18. 18 cursor.execute(sql)
  19. 19 res=cursor.fetchall()
  20. 20 close_conn(conn,cursor)
  21. 21 return res
  22. 22 def get_paper():
  23. 23 #https://www.ecva.net/papers/eccv_2020/papers_ECCV/html/343_ECCV_2020_paper.php
  24. 24 url='https://www.ecva.net/papers.php'
  25. 25 headers = {
  26. 26 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36'
  27. 27 }
  28. 28 response=requests.get(url,headers)
  29. 29 response.encoding='utf-8'
  30. 30 page_text=response.text
  31. 31 #输出页面html
  32. 32 # print(page_text)
  33. 33 soup = BeautifulSoup(page_text,'lxml')
  34. 34 all_dt=soup.find_all('dt',class_='ptitle')
  35. 35 print("dt:"+str(len(all_dt)))
  36. 36 #暂存信息
  37. 37 temp_res=[]
  38. 38 #最后结果集
  39. 39 res=[]
  40. 40 #链接
  41. 41 link_res = []
  42. 42 for dt in all_dt:
  43. 43 single_dt=str(dt)
  44. 44 single_soup=BeautifulSoup(single_dt,'lxml')
  45. 45 title=single_soup.find('a').text
  46. 46 #存标题
  47. 47 temp_res.append(title[2:])
  48. 48 #存摘要
  49. 49
  50. 50 #存关键字
  51. 51
  52. 52 #存源链接
  53. 53 sourcelink=single_soup.find('a')['href']
  54. 54 sourcelink="https://www.ecva.net/"+sourcelink
  55. 55 temp_res.append(sourcelink)
  56. 56 res.append(temp_res)
  57. 57 temp_res=[]
  58. 58 #爬取作者和pdf文件链接
  59. 59 all_dd=soup.find_all('dd')
  60. 60 print("dd:"+str(len(all_dd)))
  61. 61 flag=0
  62. 62 temp_link=[]
  63. 63 author=[] #作者列表 一层list
  64. 64 for item in all_dd:
  65. 65 if(flag%2==0):
  66. 66 #保存作者
  67. 67 author.append(item)
  68. 68 else:
  69. 69 linktext=str(item)
  70. 70 linksoup=BeautifulSoup(linktext,'lxml')
  71. 71 link_list=linksoup.find_all('a')
  72. 72 for i in link_list:
  73. 73 if(i.get('href')==None):
  74. 74 temp_link.append("fakelink")
  75. 75 else:
  76. 76 # print(i)
  77. 77 if("http" not in str(i.get('href')) and "papers" in str(i.get('href'))):
  78. 78 temp_link.append(("https://www.ecva.net/"+str(i.get('href'))))
  79. 79 else:
  80. 80 temp_link.append(i.get('href'))
  81. 81 print(temp_link)
  82. 82 link_res.append(temp_link)
  83. 83 temp_link=[]
  84. 84 #解析download 和 pdfinfo
  85. 85 flag = flag + 1
  86. 86 """
  87. 87 继续使用beautifulsoup
  88. 88 download_text 和 pdfinfo_text
  89. 89 存储author
  90. 90 "https://www.ecva.net/"
  91. 91 """
  92. 92 linkflag=1
  93. 93 print("------------------------------")
  94. 94 #把作者和download pdfinfo 存到res
  95. 95 for i in range(0,len(author)):
  96. 96 #添加作者
  97. 97 str_author=str(author[i])
  98. 98 new_author=str_author.replace("<dd>","")
  99. 99 new_author=new_author.replace(" </dd>","")
  100. 100 new_author = new_author.replace("\n", "")
  101. 101 res[i].append(new_author)
  102. 102 # print("link_res:"+str(len(link_res)))
  103. 103 if(len(link_res[i])==2):
  104. 104 #添加download
  105. 105 res[i].append(link_res[i][0])
  106. 106 #添加pdfinfo
  107. 107 res[i].append(link_res[i][1])
  108. 108 else:
  109. 109 # 添加download
  110. 110 res[i].append(link_res[i][0])
  111. 111 # 添加pdfinfo
  112. 112 res[i].append(link_res[i][2])
  113. 113 print("----------------------")
  114. 114 # print(len(author))
  115. 115 # print(len(download))
  116. 116 # print(len(pdfinfo))
  117. 117 # for item in res:
  118. 118 # print(item)
  119. 119 return res
  120. 120 #############################################################
  121. 121 #继续爬取abstract 和 keyword
  122. 122 def get_further():
  123. 123 res=get_paper()
  124. 124 temp_res=[]
  125. 125 further_res=[]
  126. 126 db_res=[]
  127. 127 sql="SELECT pdfinfo FROM pdf;"
  128. 128 db_res=query(sql) #返回元祖 要继续[0]访问数据
  129. 129 #对结果集的链接发起请求
  130. 130 for i in range(1358,len(db_res)):
  131. 131 url=db_res[i][0] #获取url
  132. 132 print(url)
  133. 133 headers={
  134. 134 "User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) "
  135. 135 "Chrome/91.0.4472.101 Safari/537.36"
  136. 136 }
  137. 137 try:
  138. 138 response=requests.get(url,headers)
  139. 139 response.encoding = "utf-8"
  140. 140 page_text = response.text
  141. 141 # print(page_text)
  142. 142 soup = BeautifulSoup(page_text, 'lxml')
  143. 143
  144. 144 abstract = soup.find('p', id='Par1').text
  145. 145 #去掉\n
  146. 146 abstract = abstract.replace("\n","")
  147. 147 print("摘要:"+abstract)
  148. 148 keyword = soup.find_all('span', class_="Keyword")
  149. 149 # print(keyword)
  150. 150 # find_keyword=re.compile('<span class="Keyword">(.*?)</span>')
  151. 151 keyword_str = ""
  152. 152 for items in keyword:
  153. 153 # 获取所有文本
  154. 154 keyword_str = keyword_str + items.get_text()
  155. 155 print("关键字:"+keyword_str)
  156. 156 #去掉 \xa0
  157. 157 keyword_str=keyword_str.replace("\xa0",",")
  158. 158 #去掉末尾的一个逗号
  159. 159 keyword_str = keyword_str[0:-1]
  160. 160 # 最后添加 摘要和关键字
  161. 161 temp_res.append(abstract)
  162. 162 temp_res.append(keyword_str)
  163. 163 further_res.append(temp_res)
  164. 164 print(temp_res)
  165. 165 print("~~~~~~~~~~~~~~~~~~~~~~~~~~~")
  166. 166 temp_res = []
  167. 167 except:
  168. 168 print("链接无效!")
  169. 169 try:
  170. 170 if(len(further_res[i][0])==0):
  171. 171 res[i].append("no abstract")
  172. 172 else:
  173. 173 res[i].append(further_res[i][0])
  174. 174 if(len(further_res[i][1])==0):
  175. 175 res[i].append("no keyword")
  176. 176 else:
  177. 177 res[i].append(further_res[i][1])
  178. 178 print(res[i])
  179. 179 # 插入数据库
  180. 180 # insert_paper_1(res[i], i)
  181. 181 except:
  182. 182 print("IndexError: list index out of range")
  183. 183 return
  184. 184
  185. 185 #连接数据库 获取游标
  186. 186 def get_conn():
  187. 187 """
  188. 188 :return: 连接,游标
  189. 189 """
  190. 190 # 创建连接
  191. 191 conn = pymysql.connect(host="127.0.0.1",
  192. 192 user="root",
  193. 193 password="000429",
  194. 194 db="paperinfo",
  195. 195 charset="utf8")
  196. 196 # 创建游标
  197. 197 cursor = conn.cursor() # 执行完毕返回的结果集默认以元组显示
  198. 198 if ((conn != None) & (cursor != None)):
  199. 199 print("数据库连接成功!游标创建成功!")
  200. 200 else:
  201. 201 print("数据库连接失败!")
  202. 202 return conn, cursor
  203. 203 #关闭数据库连接和游标
  204. 204 def close_conn(conn, cursor):
  205. 205 if cursor:
  206. 206 cursor.close()
  207. 207 if conn:
  208. 208 conn.close()
  209. 209 return 1
  210. 210 def insert_paper_0():
  211. 211 conn,cursor=get_conn()
  212. 212 res=get_paper()
  213. 213 print(f"{time.asctime()}开始插入论文详情数据")
  214. 214 try:
  215. 215 sql = "insert into paper (title,sourcelink,author,download,abstract,keyword) values(%s,%s," 216 "%s,%s,%s,%s)"
  216. 217 for item in res:
  217. 218 print(item)
  218. 219 # 异常捕获,防止数据库主键冲突
  219. 220 try:
  220. 221 cursor.execute(sql, [item[0], item[1], item[2], item[3],"",""])
  221. 222 except pymysql.err.IntegrityError:
  222. 223 print("重复!")
  223. 224 print("###########################")
  224. 225 conn.commit() # 提交事务 update delete insert操作
  225. 226 print(f"{time.asctime()}插入论文详情数据完毕")
  226. 227 except:
  227. 228 traceback.print_exc()
  228. 229 finally:
  229. 230 close_conn(conn, cursor)
  230. 231 return
  231. 232 #########################################
  232. 233 def insert_paper_1(res,count):
  233. 234 conn,cursor=get_conn()
  234. 235 print(f"{time.asctime()}开始插入论文详情数据")
  235. 236 try:
  236. 237 sql = "insert into paper (title,sourcelink,author,download,abstract,keyword) values(%s,%s," 238 "%s,%s,%s,%s)"
  237. 239 print(res)
  238. 240 # 异常捕获,防止数据库主键冲突
  239. 241 try:
  240. 242 cursor.execute(sql, [res[0], res[1], res[2], res[3],res[5],res[6]])
  241. 243 except pymysql.err.IntegrityError:
  242. 244 print("重复!")
  243. 245 print("###########################")
  244. 246 conn.commit() # 提交事务 update delete insert操作
  245. 247 print(f"{time.asctime()}插入第"+str(count+1)+"条论文详情数据完毕")
  246. 248 except:
  247. 249 traceback.print_exc()
  248. 250 finally:
  249. 251 close_conn(conn, cursor)
  250. 252 return
  251. 253
  252. 254 #单独插入 pdfinfo
  253. 255 def inseet_pdf():
  254. 256 conn, cursor = get_conn()
  255. 257 res=get_paper()
  256. 258 print(f"{time.asctime()}开始插入论文pdfinfo数据")
  257. 259 try:
  258. 260 sql = "insert into pdf (id,pdfinfo) values(%s,%s)"
  259. 261 # 异常捕获,防止数据库主键冲突
  260. 262 for item in res:
  261. 263 print(item)
  262. 264 # 异常捕获,防止数据库主键冲突
  263. 265 try:
  264. 266 cursor.execute(sql, [0,item[4]])
  265. 267 except pymysql.err.IntegrityError:
  266. 268 print("重复!")
  267. 269 print("###########################")
  268. 270 conn.commit() # 提交事务 update delete insert操作
  269. 271 print(f"{time.asctime()}插入论文pdfinfo完毕")
  270. 272 except:
  271. 273 traceback.print_exc()
  272. 274 finally:
  273. 275 close_conn(conn, cursor)
  274. 276 return
  275. 277 if (__name__=='__main__'):
  276. 278 get_further()
  277. 279 # inseet_pdf()

 

 

原文链接:http://www.cnblogs.com/rainbow-1/p/14880491.html

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号