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

news/2024/7/19 12:35:02 标签: 爬虫, 数据库, python

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

 

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

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

步骤一:获取http://bbs.baobeihuijia.com/forum-191-1.html这个版块上的所有分页页面链接

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

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

 

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

 

 

1、获取http://bbs.baobeihuijia.com/forum-191-1.html这个版块上的所有分页页面链接

 

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

BeautifulSoup形式:

[python] view plain copy

  1. def GetALLPageUrl(siteUrl):  
  2. #设置代理IP访问  
  3. #代理IP可以上http://http.zhimaruanjian.com/获取  
  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. #http://bbs.baobeihuijia.com/forum-191-1.html变成http://bbs.baobeihuijia.com,以便组成页面链接  
  14. siteindex=siteUrl.rfind("/")  
  15. tempsiteurl=siteUrl[0:siteindex+1]#http://bbs.baobeihuijia.com/  
  16. tempbianhaoqian=siteUrl[siteindex+1:-6]#forum-191-  
  17. #爬取想要的信息  
  18. bianhao=[]#存储页面编号  
  19. pageUrl=[]#存储页面链接  
  20. templist1=bsObj.find("div",{"class":"pg"})  
  21. for templist2 in templist1.findAll("a",href=re.compile("forum-([0-9]+)-([0-9]+).html")):  
  22. lianjie=templist2.attrs['href']  
  23. #print(lianjie)  
  24. index1=lianjie.rfind("-")#查找-在字符串中的位置  
  25. index2=lianjie.rfind(".")#查找.在字符串中的位置  
  26. tempbianhao=lianjie[index1+1:index2]  
  27. bianhao.append(int(tempbianhao))  
  28. bianhaoMax=max(bianhao)#获取页面的最大编号  
  29. for i in range(1,bianhaoMax+1):  
  30. temppageUrl=tempsiteurl+tempbianhaoqian+str(i)+".html"#组成页面链接  
  31. #print(temppageUrl)  
  32. pageUrl.append(temppageUrl)  
  33. return pageUrl#返回页面链接列表  

 

Selenium形式:

[python] view plain copy

  1. #得到当前板块所有的页面链接  
  2. #siteUrl为当前版块的页面链接  
  3. def GetALLPageUrl(siteUrl):  
  4. #设置代理IP访问  
  5. #代理IP可以上http://http.zhimaruanjian.com/获取  
  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. 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. #driver.implicitly_wait(30)  
  17. try:  
  18. driver.get(siteUrl)#登陆两次  
  19. driver.get(siteUrl)  
  20. except TimeoutError:  
  21. driver.refresh()  
  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. #print(bsObj.find('title').get_text())  
  31. #html.close()  
  32. except UnicodeDecodeError as e:  
  33. print("-----UnicodeDecodeError url",siteUrl)  
  34. except urllib.error.URLError as e:  
  35. print("-----urlError url:",siteUrl)  
  36. except socket.timeout as e:  
  37. print("-----socket timout:",siteUrl)  
  38. while(bsObj.find('title').get_text() == "页面重载开启"):  
  39. print("当前页面不是重加载后的页面,程序会尝试刷新一次到跳转后的页面\n")  
  40. driver.get(siteUrl)  
  41. html=driver.page_source#将浏览器执行后的源代码赋给html  
  42. bsObj=BeautifulSoup(html,"html.parser")  
  43. except Exception as e:  
  44. driver.close() # Close the current window.  
  45. driver.quit()#关闭chrome浏览器  
  46. #time.sleep()  
  47. driver.close() # Close the current window.  
  48. driver.quit()#关闭chrome浏览器  
  49. #http://bbs.baobeihuijia.com/forum-191-1.html变成http://bbs.baobeihuijia.com,以便组成页面链接  
  50. siteindex=siteUrl.rfind("/")  
  51. tempsiteurl=siteUrl[0:siteindex+1]#http://bbs.baobeihuijia.com/  
  52. tempbianhaoqian=siteUrl[siteindex+1:-6]#forum-191-  
  53. #爬取想要的信息  
  54. bianhao=[]#存储页面编号  
  55. pageUrl=[]#存储页面链接  
  56. templist1=bsObj.find("div",{"class":"pg"})  
  57. #if templist1==None:  
  58. #return  
  59. for templist2 in templist1.findAll("a",href=re.compile("forum-([0-9]+)-([0-9]+).html")):  
  60. if templist2==None:  
  61. continue  
  62. lianjie=templist2.attrs['href']  
  63. #print(lianjie)  
  64. index1=lianjie.rfind("-")#查找-在字符串中的位置  
  65. index2=lianjie.rfind(".")#查找.在字符串中的位置  
  66. tempbianhao=lianjie[index1+1:index2]  
  67. bianhao.append(int(tempbianhao))  
  68. bianhaoMax=max(bianhao)#获取页面的最大编号  
  69. for i in range(1,bianhaoMax+1):  
  70. temppageUrl=tempsiteurl+tempbianhaoqian+str(i)+".html"#组成页面链接  
  71. print(temppageUrl)  
  72. pageUrl.append(temppageUrl)  
  73. return pageUrl#返回页面链接列表  

 

 

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

 

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

所以写了以下的代码:

BeautifulSoup形式:

[python] view plain copy

  1. #得到当前版块页面所有帖子的链接  
  2. def GetCurrentPageTieziUrl(PageUrl):  
  3. #设置代理IP访问  
  4. #代理IP可以上http://http.zhimaruanjian.com/获取  
  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. #http://bbs.baobeihuijia.com/forum-191-1.html变成http://bbs.baobeihuijia.com,以便组成帖子链接  
  15. siteindex=PageUrl.rfind("/")  
  16. tempsiteurl=PageUrl[0:siteindex+1]#http://bbs.baobeihuijia.com/  
  17. #print(tempsiteurl)  
  18. TieziUrl=[]  
  19. #爬取想要的信息  
  20. for templist1 in bsObj.findAll("tbody",id=re.compile("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 copy

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

 

 

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

 

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

BeautifulSoup形式:

[python] view plain copy

  1. #得到当前页面失踪人口信息  
  2. #pageUrl为当前帖子页面链接  
  3. def CurrentPageMissingPopulationInformation(tieziUrl):  
  4. #设置代理IP访问  
  5. #代理IP可以上http://http.zhimaruanjian.com/获取  
  6. proxy_handler=urllib.request.ProxyHandler({'post':'210.136.17.78: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. req=request.Request(tieziUrl,headers=headers1 or headers2 or headers3)  
  12. html=urlopen(req)  
  13. bsObj=BeautifulSoup(html.read(),"html.parser")  
  14. html.close()  
  15. #查找想要的信息  
  16. templist1=bsObj.find("td",{"class":"t_f"}).ul  
  17. if templist1==None:#判断是否不包含ul字段,如果不,跳出函数  
  18. return  
  19. mycsv=['NULL','NULL','NULL','NULL','NULL','NULL','NULL','NULL']#初始化提取信息列表  
  20. for templist2 in templist1.findAll("font",size=re.compile("^([0-9]+)*$")):  
  21. if len(templist2)==0:  
  22. continue  
  23. tempText=templist2.get_text()  
  24. #print(tempText[0:4])  
  25. if "宝贝回家编号" in tempText[0:6]:  
  26. print(tempText)  
  27. index=tempText.find(":")  
  28. tempText=tempText[index+1:]  
  29. #mycsv.append(tempText)  
  30. if len(tempText)==0:  
  31. tempText="NULL"  
  32. mycsv[0]=tempText  
  33. if "寻亲编号" in tempText[0:6]:  
  34. print(tempText)  
  35. index=tempText.find(":")  
  36. tempText=tempText[index+1:]  
  37. if len(tempText)==0:  
  38. tempText="NULL"  
  39. #mycsv.append(tempText)  
  40. mycsv[0]=tempText  
  41. if "登记编号" in tempText[0:6]:  
  42. print(tempText)  
  43. index=tempText.find(":")  
  44. tempText=tempText[index+1:]  
  45. if len(tempText)==0:  
  46. tempText="NULL"  
  47. #mycsv.append(tempText)  
  48. mycsv[0]=tempText  
  49. if "姓" in tempText[0:6]:  
  50. print(tempText)  
  51. index=tempText.find(":")  
  52. tempText=tempText[index+1:]  
  53. #mycsv.append(tempText)  
  54. mycsv[1]=tempText  
  55. if"性" in tempText[0:6]:  
  56. print(tempText)  
  57. index=tempText.find(":")  
  58. tempText=tempText[index+1:]  
  59. #mycsv.append(tempText)  
  60. mycsv[2]=tempText  
  61. if "出生日期" in tempText[0:6]:  
  62. print(tempText)  
  63. index=tempText.find(":")  
  64. tempText=tempText[index+1:]  
  65. #mycsv.append(tempText)  
  66. mycsv[3]=tempText  
  67. if "失踪时身高" in tempText[0:6]:  
  68. print(tempText)  
  69. index=tempText.find(":")  
  70. tempText=tempText[index+1:]  
  71. #mycsv.append(tempText)  
  72. mycsv[4]=tempText  
  73. if "失踪时间" in tempText[0:6]:  
  74. print(tempText)  
  75. index=tempText.find(":")  
  76. tempText=tempText[index+1:]  
  77. #mycsv.append(tempText)  
  78. mycsv[5]=tempText  
  79. if "失踪日期" in tempText[0:6]:  
  80. print(tempText)  
  81. index=tempText.find(":")  
  82. tempText=tempText[index+1:]  
  83. #mycsv.append(tempText)  
  84. mycsv[5]=tempText  
  85. if "失踪地点" in tempText[0:6]:  
  86. print(tempText)  
  87. index=tempText.find(":")  
  88. tempText=tempText[index+1:]  
  89. #mycsv.append(tempText)  
  90. mycsv[6]=tempText  
  91. if "是否报案" in tempText[0:6]:  
  92. print(tempText)  
  93. index=tempText.find(":")  
  94. tempText=tempText[index+1:]  
  95. #mycsv.append(tempText)  
  96. mycsv[7]=tempText  
  97. try:  
  98. 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文件  
  99. finally:  
  100. time.sleep(1)#设置爬完之后的睡眠时间,这里先设置为1秒  

 

Selenium形式:

[python] view plain copy

  1. #得到当前页面失踪人口信息  
  2. #pageUrl为当前帖子页面链接  
  3. def CurrentPageMissingPopulationInformation(tieziUrl):  
  4. #设置代理IP访问  
  5. #代理IP可以上http://http.zhimaruanjian.com/获取  
  6. proxy_handler=urllib.request.ProxyHandler({'post':'128.199.169.17:80'})  
  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. 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. #driver.implicitly_wait(30)  
  17. try:  
  18. driver.get(tieziUrl)#登陆两次  
  19. driver.get(tieziUrl)  
  20. except TimeoutError:  
  21. driver.refresh()  
  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",tieziUrl)  
  33. except urllib.error.URLError as e:  
  34. print("-----urlError url:",tieziUrl)  
  35. except socket.timeout as e:  
  36. print("-----socket timout:",tieziUrl)  
  37. while(bsObj.find('title').get_text() == "页面重载开启"):  
  38. print("当前页面不是重加载后的页面,程序会尝试刷新一次到跳转后的页面\n")  
  39. driver.get(tieziUrl)  
  40. html=driver.page_source#将浏览器执行后的源代码赋给html  
  41. bsObj=BeautifulSoup(html,"html.parser")  
  42. except Exception as e:  
  43. driver.close() # Close the current window.  
  44. driver.quit()#关闭chrome浏览器  
  45. time.sleep(0.5)  
  46. driver.close() # Close the current window.  
  47. driver.quit()#关闭chrome浏览器  
  48. #查找想要的信息  
  49. templist1=bsObj.find("td",{"class":"t_f"}).ul  
  50. if templist1==None:#判断是否不包含ul字段,如果不,跳出函数  
  51. print("当前帖子页面不包含ul字段")  
  52. return 1  
  53. mycsv=['NULL','NULL','NULL','NULL','NULL','NULL','NULL','NULL']#初始化提取信息列表  
  54. for templist2 in templist1.findAll("font",size=re.compile("^([0-9]+)*$")):  
  55. tempText=templist2.get_text()  
  56. #print(tempText[0:4])  
  57. if "宝贝回家编号" in tempText[0:6]:  
  58. print(tempText)  
  59. index=tempText.find(":")  
  60. tempText=tempText[index+1:]  
  61. #mycsv.append(tempText)  
  62. if len(tempText)==0:  
  63. tempText="NULL"  
  64. mycsv[0]=tempText  
  65. if "寻亲编号" in tempText[0:6]:  
  66. print(tempText)  
  67. index=tempText.find(":")  
  68. tempText=tempText[index+1:]  
  69. if len(tempText)==0:  
  70. tempText="NULL"  
  71. #mycsv.append(tempText)  
  72. mycsv[0]=tempText  
  73. if "登记编号" in tempText[0:6]:  
  74. print(tempText)  
  75. index=tempText.find(":")  
  76. tempText=tempText[index+1:]  
  77. if len(tempText)==0:  
  78. tempText="NULL"  
  79. #mycsv.append(tempText)  
  80. mycsv[0]=tempText  
  81. if "姓" in tempText[0:6]:  
  82. print(tempText)  
  83. index=tempText.find(":")  
  84. tempText=tempText[index+1:]  
  85. #mycsv.append(tempText)  
  86. mycsv[1]=tempText  
  87. if"性" in tempText[0:6]:  
  88. print(tempText)  
  89. index=tempText.find(":")  
  90. tempText=tempText[index+1:]  
  91. #mycsv.append(tempText)  
  92. mycsv[2]=tempText  
  93. if "出生日期" in tempText[0:6]:  
  94. print(tempText)  
  95. index=tempText.find(":")  
  96. tempText=tempText[index+1:]  
  97. #mycsv.append(tempText)  
  98. mycsv[3]=tempText  
  99. if "失踪时身高" in tempText[0:6]:  
  100. print(tempText)  
  101. index=tempText.find(":")  
  102. tempText=tempText[index+1:]  
  103. #mycsv.append(tempText)  
  104. mycsv[4]=tempText  
  105. if "失踪时间" in tempText[0:6]:  
  106. print(tempText)  
  107. index=tempText.find(":")  
  108. tempText=tempText[index+1:]  
  109. #mycsv.append(tempText)  
  110. mycsv[5]=tempText  
  111. if "失踪日期" in tempText[0:6]:  
  112. print(tempText)  
  113. index=tempText.find(":")  
  114. tempText=tempText[index+1:]  
  115. #mycsv.append(tempText)  
  116. mycsv[5]=tempText  
  117. if "失踪地点" in tempText[0:6]:  
  118. print(tempText)  
  119. index=tempText.find(":")  
  120. tempText=tempText[index+1:]  
  121. #mycsv.append(tempText)  
  122. mycsv[6]=tempText  
  123. if "是否报案" in tempText[0:6]:  
  124. print(tempText)  
  125. index=tempText.find(":")  
  126. tempText=tempText[index+1:]  
  127. #mycsv.append(tempText)  
  128. mycsv[7]=tempText  
  129. try:  
  130. 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文件  
  131. csvfile.flush()#马上将这条数据写入csv文件中  
  132. finally:  
  133. print("当前帖子信息写入完成\n")  
  134. time.sleep(5)#设置爬完之后的睡眠时间,这里先设置为1秒  

 

 

现附上所有代码,此代码仅供参考,不能用于商业用途,网络爬虫易给网站服务器造成巨大负荷,任何人使用本代码所引起的任何后果,本人不予承担法律责任。贴出代码的初衷是供大家学习爬虫,大家只是研究下网络框架即可,不要使用此代码去加重网站负荷,本人由于不当使用,已被封IP,前车之鉴,爬取失踪人口信息只是为了从空间上分析人口失踪的规律,由此给网站造成的什么不便,请见谅。

 

 

附上所有代码:

[python] view plain copy

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

 

 

 

 

写成的CSV文件截图:

 

 

转载于:https://www.cnblogs.com/zhimaHTTP/p/7728087.html


http://www.niftyadmin.cn/n/1505492.html

相关文章

grep中的-q

-q, --quiet, --silent Quiet; do not write anything to standard output. Exit immediately with zero status if any match is found, even if an error was detected. Also see the -s or --no-messages option. (-q is specified by POSIX.)转载于:https://www.cnblogs.co…

妙用VHD,多操作系统更换不再是难事

前提&#xff1a; 1&#xff0c;系统必须是支持VHD启动&#xff0c;如果不支持&#xff0c;那就不要白折腾了。 2&#xff0c;这里只演示双系统安装&#xff0c;在原有小7的基础上安装小8&#xff0c;实现双系统并存。 3&#xff0c;所用到的工具为&#xff1a;AIK里面…

Android Notification通知的总结(兼容8.0+和8.0以下)

先上视频效果&#xff0c;左边是提醒式通知&#xff08;弹横幅&#xff09;&#xff0c;右边是普通通知&#xff0c;通过Demo上的按键触发&#xff0c;解析一段写好的json拿到通知要显示的数据&#xff0c;然后弹notification&#xff1a; 有如下需要注意的几个关键点&#xff…

一句话木马的使用

实验准备 首先保存一个一句话木马文件Untitled-1.php <?php eval($_POST[pass]);?>DVWA平台 中国蚁剑 实验步骤 首先进入DVWA平台&#xff0c;选择LOW安全级别 在low安全级别中&#xff0c;网站未对上传的文件进行任何验证所以可以直接上传PHP或ASP一句话木马&…

字节序和网络字节序【转】

1 字节序由于不同的计算机系统采用不同的字节序存储数据,同样一个4字节的32位整数,在内存中存储的方式就不同. 字节序分为小尾字节序(Little Endian)和大尾字节序(Big Endian), Intel处理器大多数使用小尾字节序, Motorola处理器大多数使用大尾(Big Endian)字节序;小尾就…

【考试总结】AHSOFNUQZQZ test10-25

Tips&#xff1a; 1.评测在 Windows 下的 lemon 中进行&#xff0c;开启 O2 优化&#xff0c;开大栈空间&#xff1b; 2.题目较水&#xff0c;无论 AK 与否&#xff0c;都请不要 D 出题人。 题目名称 切题 开车 学习 英文名称 problem car study 输入文件名 problem.in car.in …

Android ImageView.ScaleType的几种类别

CENTER 居中显示图片&#xff0c;但图片不会被缩放&#xff1b; CENTER_CROP 居中显示图片&#xff0c;对图片等比缩放&#xff08;保持图片的长宽比&#xff09;&#xff0c;缩放后的图片长宽中较小的值能铺满ImageView控件&#xff1b; CENTER_INSIDE 居中显示图片&#xff0…

ios开发 各种动画效果

.h文件中 interface ViewController:UIViewController {IBOutlet UIImageView *imageView; } 一、UIView 简单的动画效果&#xff08;UIViewAnimation&#xff09; 1.向上翻页 [UIView beginAnimations:"animationID" context:nil]; [UIView setAnimationDuration:8]…