失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > Python爬虫小实践:寻找失踪人口 爬取失踪儿童信息并写成csv文件 方便存入数据库

Python爬虫小实践:寻找失踪人口 爬取失踪儿童信息并写成csv文件 方便存入数据库

时间:2023-06-21 04:08:25

相关推荐

Python爬虫小实践:寻找失踪人口 爬取失踪儿童信息并写成csv文件 方便存入数据库

前两天有人私信我,让我爬这个网站,/f...上的失踪儿童信息,准备根据失踪儿童的失踪时的地理位置来更好的寻找失踪儿童,这种事情本就应该义不容辞,如果对网站服务器造成负荷,还请谅解。

这次依然是用第三方爬虫包BeautifulSoup,还有Selenium+Chrome,Selenium+PhantomJS来爬取信息。

通过分析网站的框架,依然分三步来进行。

步骤一:获取/f...这个版块上的所有分页页面链接

步骤二:获取每一个分页链接上所发的帖子的链接

步骤三:获取每一个帖子链接上要爬取的信息,编号,姓名,性别,出生日期,失踪时身高,失踪时间,失踪地点,以及是否报案

起先用的BeautifulSoup,但是被管理员设置了网站重定向,然后就采用selenium的方式,在这里还是对网站管理员说一声抱歉。

1、获取/f...这个版块上的所有分页页面链接

通过分析:发现分页的页面链接处于<div class="pg">下,所以写了以下的代码

BeautifulSoup形式:

'''想要学习Python?Python学习交流群:984632579满足你的需求,资料都已经上传群文件,可以自行下载!'''1.def GetALLPageUrl(siteUrl): 2. #设置代理IP访问 3. #代理IP可以上/获取 4. proxy_handler=urllib.request.ProxyHandler({'https':'111.76.129.200:808'}) 5. proxy_auth_handler=urllib.request.ProxyBasicAuthHandler() 6. opener = urllib.request.build_opener(urllib.request.HTTPHandler, proxy_handler) 7. urllib.request.install_opener(opener) 8. #获取网页信息 9. req=request.Request(siteUrl,headers=headers1 or headers2 or headers3) 10. html=urlopen(req) 11. bsObj=BeautifulSoup(html.read(),"html.parser") 12. html.close() 13. #/forum-191-1.html变成,以便组成页面链接 14. siteindex=siteUrl.rfind("/") 15. tempsiteurl=siteUrl[0:siteindex+1]#/ 16. tempbianhaoqian=siteUrl[siteindex+1:-6]#forum-191- 17. 18. #爬取想要的信息 19. bianhao=[]#存储页面编号 20. pageUrl=[]#存储页面链接 21. templist1=bsObj.find("div",{"class":"pg"}) 22. for templist2 in templist1.findAll("a",href=pile("forum-([0-9]+)-([0-9]+).html")): 23. lianjie=templist2.attrs['href'] 24. #print(lianjie) 25. index1=lianjie.rfind("-")#查找-在字符串中的位置 26. index2=lianjie.rfind(".")#查找.在字符串中的位置 27. tempbianhao=lianjie[index1+1:index2] 28. bianhao.append(int(tempbianhao)) 29. bianhaoMax=max(bianhao)#获取页面的最大编号 30. 31. for i in range(1,bianhaoMax+1): 32. temppageUrl=tempsiteurl+tempbianhaoqian+str(i)+".html"#组成页面链接 33. #print(temppageUrl) 34. pageUrl.append(temppageUrl) 35. return pageUrl#返回页面链接列表 Selenium形式:[python] view plain copy1.#得到当前板块所有的页面链接 2.#siteUrl为当前版块的页面链接 3.def GetALLPageUrl(siteUrl): 4. #设置代理IP访问 5. #代理IP可以上/获取 6. proxy_handler=urllib.request.ProxyHandler({'post':'123.207.143.51:8080'}) 7. proxy_auth_handler=urllib.request.ProxyBasicAuthHandler() 8. opener = urllib.request.build_opener(urllib.request.HTTPHandler, proxy_handler) 9. urllib.request.install_opener(opener) 10. 11. try: 12. #掉用第三方包selenium打开浏览器登陆 13. #driver=webdriver.Chrome()#打开chrome 14. driver=webdriver.Chrome()#打开无界面浏览器Chrome 15. #driver=webdriver.PhantomJS()#打开无界面浏览器PhantomJS 16. driver.set_page_load_timeout(10) 17. #driver.implicitly_wait(30) 18. try: 19. driver.get(siteUrl)#登陆两次 20. driver.get(siteUrl) 21. except TimeoutError: 22. driver.refresh() 23. 24. #print(driver.page_source) 25. html=driver.page_source#将浏览器执行后的源代码赋给html 26. #获取网页信息 27. #抓捕网页解析过程中的错误 28. try: 29. #req=request.Request(tieziUrl,headers=headers5) 30. #html=urlopen(req) 31. bsObj=BeautifulSoup(html,"html.parser") 32. #print(bsObj.find('title').get_text()) 33. #html.close() 34. except UnicodeDecodeError as e: 35. print("-----UnicodeDecodeError url",siteUrl) 36. except urllib.error.URLError as e: 37. print("-----urlError url:",siteUrl) 38. except socket.timeout as e: 39. print("-----socket timout:",siteUrl) 40. 41. 42. 43. while(bsObj.find('title').get_text() == "页面重载开启"): 44. print("当前页面不是重加载后的页面,程序会尝试刷新一次到跳转后的页面\n") 45. driver.get(siteUrl) 46. html=driver.page_source#将浏览器执行后的源代码赋给html 47. bsObj=BeautifulSoup(html,"html.parser") 48. except Exception as e: 49. 50. driver.close() # Close the current window. 51. driver.quit()#关闭chrome浏览器 52. #time.sleep() 53. 54. driver.close() # Close the current window. 55. driver.quit()#关闭chrome浏览器 56. 57. 58. #/forum-191-1.html变成,以便组成页面链接 59. siteindex=siteUrl.rfind("/") 60. tempsiteurl=siteUrl[0:siteindex+1]#/ 61. tempbianhaoqian=siteUrl[siteindex+1:-6]#forum-191- 62. 63. #爬取想要的信息 64. bianhao=[]#存储页面编号 65. pageUrl=[]#存储页面链接 66. 67. templist1=bsObj.find("div",{"class":"pg"}) 68. #if templist1==None: 69. #return 70. for templist2 in templist1.findAll("a",href=pile("forum-([0-9]+)-([0-9]+).html")): 71. if templist2==None: 72. continue 73. lianjie=templist2.attrs['href'] 74. #print(lianjie) 75. index1=lianjie.rfind("-")#查找-在字符串中的位置 76. index2=lianjie.rfind(".")#查找.在字符串中的位置 77. tempbianhao=lianjie[index1+1:index2] 78. bianhao.append(int(tempbianhao)) 79. bianhaoMax=max(bianhao)#获取页面的最大编号 80. 81. for i in range(1,bianhaoMax+1): 82. temppageUrl=tempsiteurl+tempbianhaoqian+str(i)+".html"#组成页面链接 83. print(temppageUrl) 84. pageUrl.append(temppageUrl) 85. return pageUrl#返回页面链接列表

2.获取每一个分页链接上所发的帖子的链接

每个帖子的链接都位于href下

所以写了以下的代码:

BeautifulSoup形式:

1.#得到当前版块页面所有帖子的链接 2.def GetCurrentPageTieziUrl(PageUrl): 3. #设置代理IP访问 4. #代理IP可以上/获取 5. proxy_handler=urllib.request.ProxyHandler({'post':'121.22.252.85:8000'}) 6. proxy_auth_handler=urllib.request.ProxyBasicAuthHandler() 7. opener = urllib.request.build_opener(urllib.request.HTTPHandler, proxy_handler) 8. urllib.request.install_opener(opener) 9. #获取网页信息 10. req=request.Request(PageUrl,headers=headers1 or headers2 or headers3) 11. html=urlopen(req) 12. bsObj=BeautifulSoup(html.read(),"html.parser") 13. html.close() 14. #/forum-191-1.html变成,以便组成帖子链接 15. siteindex=PageUrl.rfind("/") 16. tempsiteurl=PageUrl[0:siteindex+1]#/ 17. #print(tempsiteurl) 18. TieziUrl=[] 19. #爬取想要的信息 20. for templist1 in bsObj.findAll("tbody",id=pile("normalthread_([0-9]+)")) : 21. for templist2 in templist1.findAll("a",{"class":"s xst"}): 22. tempteiziUrl=tempsiteurl+templist2.attrs['href']#组成帖子链接 23. print(tempteiziUrl) 24. TieziUrl.append(tempteiziUrl) 25. return TieziUrl#返回帖子链接列表 Selenium形式:[python] view plain copy1.#得到当前版块页面所有帖子的链接 2.def GetCurrentPageTieziUrl(PageUrl): 3. #设置代理IP访问 4. #代理IP可以上/获取 5. proxy_handler=urllib.request.ProxyHandler({'post':'110.73.30.157:8123'}) 6. proxy_auth_handler=urllib.request.ProxyBasicAuthHandler() 7. opener = urllib.request.build_opener(urllib.request.HTTPHandler, proxy_handler) 8. urllib.request.install_opener(opener) 9. 10. try: 11. #掉用第三方包selenium打开浏览器登陆 12. #driver=webdriver.Chrome()#打开chrome 13. driver=webdriver.Chrome()#打开无界面浏览器Chrome 14. #driver=webdriver.PhantomJS()#打开无界面浏览器PhantomJS 15. driver.set_page_load_timeout(10) 16. try: 17. driver.get(PageUrl)#登陆两次 18. driver.get(PageUrl) 19. except TimeoutError: 20. driver.refresh() 21. 22. #print(driver.page_source) 23. html=driver.page_source#将浏览器执行后的源代码赋给html 24. #获取网页信息 25. #抓捕网页解析过程中的错误 26. try: 27. #req=request.Request(tieziUrl,headers=headers5) 28. #html=urlopen(req) 29. bsObj=BeautifulSoup(html,"html.parser") 30. #html.close() 31. except UnicodeDecodeError as e: 32. print("-----UnicodeDecodeError url",PageUrl) 33. except urllib.error.URLError as e: 34. print("-----urlError url:",PageUrl) 35. except socket.timeout as e: 36. print("-----socket timout:",PageUrl) 37. 38. n=0 39. while(bsObj.find('title').get_text() == "页面重载开启"): 40. print("当前页面不是重加载后的页面,程序会尝试刷新一次到跳转后的页面\n") 41. driver.get(PageUrl) 42. html=driver.page_source#将浏览器执行后的源代码赋给html 43. bsObj=BeautifulSoup(html,"html.parser") 44. n=n+1 45. if n==10: 46.driver.close() # Close the current window. 47.driver.quit()#关闭chrome浏览器 48.return 1 49. 50. except Exception as e: 51. driver.close() # Close the current window. 52. driver.quit()#关闭chrome浏览器 53. time.sleep(1) 54. 55. driver.close() # Close the current window. 56. driver.quit()#关闭chrome浏览器 57. 58. 59. #/forum-191-1.html变成,以便组成帖子链接 60. siteindex=PageUrl.rfind("/") 61. tempsiteurl=PageUrl[0:siteindex+1]#/ 62. #print(tempsiteurl) 63. TieziUrl=[] 64. #爬取想要的信息 65. for templist1 in bsObj.findAll("tbody",id=pile("normalthread_([0-9]+)")) : 66. if templist1==None: 67. continue 68. for templist2 in templist1.findAll("a",{"class":"s xst"}): 69. if templist2==None: 70.continue 71. tempteiziUrl=tempsiteurl+templist2.attrs['href']#组成帖子链接 72. print(tempteiziUrl) 73. TieziUrl.append(tempteiziUrl) 74. return TieziUrl#返回帖子链接列表

3.获取每一个帖子链接上要爬取的信息,编号,姓名,性别,出生日期,失踪时身高,失踪时间,失踪地点,以及是否报案,并写入CSV中

通过查看每一个帖子的链接,发现其失踪人口信息都在<ul>标签下,所以编写了以下的代码

所有代码

1.#__author__ = 'Administrator' 2.#coding=utf-8 3.import io 4.import os 5.import sys 6.import math 7.import urllib 8.from urllib.request import urlopen 9.from urllib.request import urlretrieve 10.from urllib import request 11.from bs4 import BeautifulSoup 12.import re 13.import time 14.import socket 15.import csv 16.from selenium import webdriver 17. 18.socket.setdefaulttimeout(5000)#设置全局超时函数 19. 20. 21. 22.sys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding='gb18030') 23.#sys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding='utf-8') 24.#设置不同的headers,伪装为不同的浏览器 25.headers1={'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:23.0) Gecko/0101 Firefox/23.0'} 26.headers2={'User-Agent':'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36'} 27.headers3={'User-Agent':'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11'} 28.headers4={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.104 Safari/537.36 Core/1.53.2372.400 QQBrowser/9.5.10548.400'} 29.headers5={'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8', 30.'Connection':'keep-alive', 31.'Host':'', 32.'Referer':'/forum-191-1.html', 33.'Upgrade-Insecure-Requests':'1', 34.'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36'} 35. 36.headers6={'Host': '', 37.'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:51.0) Gecko/0101 Firefox/51.0', 38.'Accept': 'textml,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 39.'Connection': 'keep-alive', 40.'Upgrade-Insecure-Requests':' 1' 41.} 42.#得到当前页面失踪人口信息 43.#pageUrl为当前帖子页面链接 44.def CurrentPageMissingPopulationInformation(tieziUrl): 45. #设置代理IP访问 46. #代理IP可以上/获取 47. proxy_handler=urllib.request.ProxyHandler({'post':'128.199.169.17:80'}) 48. proxy_auth_handler=urllib.request.ProxyBasicAuthHandler() 49. opener = urllib.request.build_opener(urllib.request.HTTPHandler, proxy_handler) 50. urllib.request.install_opener(opener) 51. 52. try: 53. #掉用第三方包selenium打开浏览器登陆 54. #driver=webdriver.Chrome()#打开chrome 55. driver=webdriver.Chrome()#打开无界面浏览器Chrome 56. #driver=webdriver.PhantomJS()#打开无界面浏览器PhantomJS 57. driver.set_page_load_timeout(10) 58. #driver.implicitly_wait(30) 59. try: 60. driver.get(tieziUrl)#登陆两次 61. driver.get(tieziUrl) 62. except TimeoutError: 63. driver.refresh() 64. 65. #print(driver.page_source) 66. html=driver.page_source#将浏览器执行后的源代码赋给html 67. #获取网页信息 68. #抓捕网页解析过程中的错误 69. try: 70. #req=request.Request(tieziUrl,headers=headers5) 71. #html=urlopen(req) 72. bsObj=BeautifulSoup(html,"html.parser") 73. #html.close() 74. except UnicodeDecodeError as e: 75. print("-----UnicodeDecodeError url",tieziUrl) 76. except urllib.error.URLError as e: 77. print("-----urlError url:",tieziUrl) 78. except socket.timeout as e: 79. print("-----socket timout:",tieziUrl) 80. 81. 82. while(bsObj.find('title').get_text() == "页面重载开启"): 83. print("当前页面不是重加载后的页面,程序会尝试刷新一次到跳转后的页面\n") 84. driver.get(tieziUrl) 85. html=driver.page_source#将浏览器执行后的源代码赋给html 86. bsObj=BeautifulSoup(html,"html.parser") 87. except Exception as e: 88. driver.close() # Close the current window. 89. driver.quit()#关闭chrome浏览器 90. time.sleep(0.5) 91. 92. driver.close() # Close the current window. 93. driver.quit()#关闭chrome浏览器 94. 95. 96. #查找想要的信息 97. templist1=bsObj.find("td",{"class":"t_f"}).ul 98. if templist1==None:#判断是否不包含ul字段,如果不,跳出函数 99. print("当前帖子页面不包含ul字段") 100. return 1 101. mycsv=['NULL','NULL','NULL','NULL','NULL','NULL','NULL','NULL']#初始化提取信息列表 102. for templist2 in templist1.findAll("font",size=pile("^([0-9]+)*$")): 103. tempText=templist2.get_text() 104. #print(tempText[0:4]) 105. if "宝贝回家编号" in tempText[0:6]: 106. print(tempText) 107. index=tempText.find(":") 108. tempText=tempText[index+1:] 109. #mycsv.append(tempText) 110. if len(tempText)==0: 111.tempText="NULL" 112. mycsv[0]=tempText 113. if "寻亲编号" in tempText[0:6]: 114. print(tempText) 115. index=tempText.find(":") 116. tempText=tempText[index+1:] 117. if len(tempText)==0: 118.tempText="NULL" 119. #mycsv.append(tempText) 120. mycsv[0]=tempText 121. if "登记编号" in tempText[0:6]: 122. print(tempText) 123. index=tempText.find(":") 124. tempText=tempText[index+1:] 125. if len(tempText)==0: 126.tempText="NULL" 127. #mycsv.append(tempText) 128. mycsv[0]=tempText 129. if "姓" in tempText[0:6]: 130. print(tempText) 131. index=tempText.find(":") 132. tempText=tempText[index+1:] 133. #mycsv.append(tempText) 134. mycsv[1]=tempText 135. if"性" in tempText[0:6]: 136. print(tempText) 137. index=tempText.find(":") 138. tempText=tempText[index+1:] 139. #mycsv.append(tempText) 140. mycsv[2]=tempText 141. if "出生日期" in tempText[0:6]: 142. print(tempText) 143. index=tempText.find(":") 144. tempText=tempText[index+1:] 145. #mycsv.append(tempText) 146. mycsv[3]=tempText 147. if "失踪时身高" in tempText[0:6]: 148. print(tempText) 149. index=tempText.find(":") 150. tempText=tempText[index+1:] 151. #mycsv.append(tempText) 152. mycsv[4]=tempText 153. if "失踪时间" in tempText[0:6]: 154. print(tempText) 155. index=tempText.find(":") 156. tempText=tempText[index+1:] 157. #mycsv.append(tempText) 158. mycsv[5]=tempText 159. if "失踪日期" in tempText[0:6]: 160. print(tempText) 161. index=tempText.find(":") 162. tempText=tempText[index+1:] 163. #mycsv.append(tempText) 164. mycsv[5]=tempText 165. if "失踪地点" in tempText[0:6]: 166. print(tempText) 167. index=tempText.find(":") 168. tempText=tempText[index+1:] 169. #mycsv.append(tempText) 170. mycsv[6]=tempText 171. if "是否报案" in tempText[0:6]: 172. print(tempText) 173. index=tempText.find(":") 174. tempText=tempText[index+1:] 175. #mycsv.append(tempText) 176. mycsv[7]=tempText 177. try: 178. writer.writerow((str(mycsv[0]),str(mycsv[1]),str(mycsv[2]),str(mycsv[3]),str(mycsv[4]),str(mycsv[5]),str(mycsv[6]),str(mycsv[7])))#写入CSV文件 179. csvfile.flush()#马上将这条数据写入csv文件中 180. finally: 181. print("当前帖子信息写入完成\n") 182. time.sleep(5)#设置爬完之后的睡眠时间,这里先设置为1秒 183. 184. 185.#得到当前板块所有的页面链接 186.#siteUrl为当前版块的页面链接 187.def GetALLPageUrl(siteUrl): 188. #设置代理IP访问 189. #代理IP可以上/获取 190. proxy_handler=urllib.request.ProxyHandler({'post':'123.207.143.51:8080'}) 191. proxy_auth_handler=urllib.request.ProxyBasicAuthHandler() 192. opener = urllib.request.build_opener(urllib.request.HTTPHandler, proxy_handler) 193. urllib.request.install_opener(opener) 194. 195. try: 196. #掉用第三方包selenium打开浏览器登陆 197. #driver=webdriver.Chrome()#打开chrome 198. driver=webdriver.Chrome()#打开无界面浏览器Chrome 199. #driver=webdriver.PhantomJS()#打开无界面浏览器PhantomJS 200. driver.set_page_load_timeout(10) 201. #driver.implicitly_wait(30) 202. try: 203. driver.get(siteUrl)#登陆两次 204. driver.get(siteUrl) 205. except TimeoutError: 206. driver.refresh() 207. 208. #print(driver.page_source) 209. html=driver.page_source#将浏览器执行后的源代码赋给html 210. #获取网页信息 211. #抓捕网页解析过程中的错误 212. try: 213. #req=request.Request(tieziUrl,headers=headers5) 214. #html=urlopen(req) 215. bsObj=BeautifulSoup(html,"html.parser") 216. #print(bsObj.find('title').get_text()) 217. #html.close() 218. except UnicodeDecodeError as e: 219. print("-----UnicodeDecodeError url",siteUrl) 220. except urllib.error.URLError as e: 221. print("-----urlError url:",siteUrl) 222. except socket.timeout as e: 223. print("-----socket timout:",siteUrl) 224. 225. 226. 227. while(bsObj.find('title').get_text() == "页面重载开启"): 228. print("当前页面不是重加载后的页面,程序会尝试刷新一次到跳转后的页面\n") 229. driver.get(siteUrl) 230. html=driver.page_source#将浏览器执行后的源代码赋给html 231. bsObj=BeautifulSoup(html,"html.parser") 232. except Exception as e: 233. 234. driver.close() # Close the current window. 235. driver.quit()#关闭chrome浏览器 236. #time.sleep() 237. 238. driver.close() # Close the current window. 239. driver.quit()#关闭chrome浏览器 240. 241. 242. #/forum-191-1.html变成,以便组成页面链接 243. siteindex=siteUrl.rfind("/") 244. tempsiteurl=siteUrl[0:siteindex+1]#/ 245. tempbianhaoqian=siteUrl[siteindex+1:-6]#forum-191- 246. 247. #爬取想要的信息 248. bianhao=[]#存储页面编号 249. pageUrl=[]#存储页面链接 250. 251. templist1=bsObj.find("div",{"class":"pg"}) 252. #if templist1==None: 253. #return 254. for templist2 in templist1.findAll("a",href=pile("forum-([0-9]+)-([0-9]+).html")): 255. if templist2==None: 256. continue 257. lianjie=templist2.attrs['href'] 258. #print(lianjie) 259. index1=lianjie.rfind("-")#查找-在字符串中的位置 260. index2=lianjie.rfind(".")#查找.在字符串中的位置 261. tempbianhao=lianjie[index1+1:index2] 262. bianhao.append(int(tempbianhao)) 263. bianhaoMax=max(bianhao)#获取页面的最大编号 264. 265. for i in range(1,bianhaoMax+1): 266. temppageUrl=tempsiteurl+tempbianhaoqian+str(i)+".html"#组成页面链接 267. print(temppageUrl) 268. pageUrl.append(temppageUrl) 269. return pageUrl#返回页面链接列表 270. 271.#得到当前版块页面所有帖子的链接 272.def GetCurrentPageTieziUrl(PageUrl): 273. #设置代理IP访问 274. #代理IP可以上/获取 275. proxy_handler=urllib.request.ProxyHandler({'post':'110.73.30.157:8123'}) 276. proxy_auth_handler=urllib.request.ProxyBasicAuthHandler() 277. opener = urllib.request.build_opener(urllib.request.HTTPHandler, proxy_handler) 278. urllib.request.install_opener(opener) 279. 280. try: 281. #掉用第三方包selenium打开浏览器登陆 282. #driver=webdriver.Chrome()#打开chrome 283. driver=webdriver.Chrome()#打开无界面浏览器Chrome 284. #driver=webdriver.PhantomJS()#打开无界面浏览器PhantomJS 285. driver.set_page_load_timeout(10) 286. try: 287. driver.get(PageUrl)#登陆两次 288. driver.get(PageUrl) 289. except TimeoutError: 290. driver.refresh() 291. 292. #print(driver.page_source) 293. html=driver.page_source#将浏览器执行后的源代码赋给html 294. #获取网页信息 295. #抓捕网页解析过程中的错误 296. try: 297. #req=request.Request(tieziUrl,headers=headers5) 298. #html=urlopen(req) 299. bsObj=BeautifulSoup(html,"html.parser") 300. #html.close() 301. except UnicodeDecodeError as e: 302. print("-----UnicodeDecodeError url",PageUrl) 303. except urllib.error.URLError as e: 304. print("-----urlError url:",PageUrl) 305. except socket.timeout as e: 306. print("-----socket timout:",PageUrl) 307. 308. n=0 309. while(bsObj.find('title').get_text() == "页面重载开启"): 310. print("当前页面不是重加载后的页面,程序会尝试刷新一次到跳转后的页面\n") 311. driver.get(PageUrl) 312. html=driver.page_source#将浏览器执行后的源代码赋给html 313. bsObj=BeautifulSoup(html,"html.parser") 314. n=n+1 315. if n==10: 316.driver.close() # Close the current window. 317.driver.quit()#关闭chrome浏览器 318.return 1 319. 320. except Exception as e: 321. driver.close() # Close the current window. 322. driver.quit()#关闭chrome浏览器 323. time.sleep(1) 324. 325. driver.close() # Close the current window. 326. driver.quit()#关闭chrome浏览器 327. 328. 329. #/forum-191-1.html变成,以便组成帖子链接 330. siteindex=PageUrl.rfind("/") 331. tempsiteurl=PageUrl[0:siteindex+1]#/ 332. #print(tempsiteurl) 333. TieziUrl=[] 334. #爬取想要的信息 335. for templist1 in bsObj.findAll("tbody",id=pile("normalthread_([0-9]+)")) : 336. if templist1==None: 337. continue 338. for templist2 in templist1.findAll("a",{"class":"s xst"}): 339. if templist2==None: 340.continue 341. tempteiziUrl=tempsiteurl+templist2.attrs['href']#组成帖子链接 342. print(tempteiziUrl) 343. TieziUrl.append(tempteiziUrl) 344. return TieziUrl#返回帖子链接列表 345. 346. 347. 348.#CurrentPageMissingPopulationInformation("/thread-213126-1-1.html") 349.#GetALLPageUrl("/forum-191-1.html") 350.#GetCurrentPageTieziUrl("/forum-191-1.html") 351. 352.if __name__ == '__main__': 353. csvfile=open("E:/MissingPeople.csv","w+",newline="",encoding='gb18030') 354. writer=csv.writer(csvfile) 355. writer.writerow(('宝贝回家编号','姓名','性别','出生日期','失踪时身高','失踪时间','失踪地点','是否报案')) 356. pageurl=GetALLPageUrl("/forum-191-1.html")#寻找失踪宝贝 357. #pageurl=GetALLPageUrl("/forum-189-1.html")#被拐宝贝回家 358. time.sleep(5) 359. print("所有页面链接获取成功!\n") 360. n=0 361. for templist1 in pageurl: 362. #print(templist1) 363. tieziurl=GetCurrentPageTieziUrl(templist1) 364. time.sleep(5) 365. print("当前页面"+str(templist1)+"所有帖子链接获取成功!\n") 366. if tieziurl ==1: 367. print("不能得到当前帖子页面!\n") 368. continue 369. else: 370. for templist2 in tieziurl: 371. #print(templist2) 372.n=n+1 373.print("\n正在收集第"+str(n)+"条信息!") 374.time.sleep(5) 375.tempzhi=CurrentPageMissingPopulationInformation(templist2) 376.if tempzhi==1: 377. print("\n第"+str(n)+"条信息为空!") 378. continue 379. print('') 380. print("信息爬取完成!请放心的关闭程序!") 381. csvfile.close()

写成的CSV文件截图:

转载:/a/1190000011692301

如果觉得《Python爬虫小实践:寻找失踪人口 爬取失踪儿童信息并写成csv文件 方便存入数据库》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。