前两天有人私信我,让我爬这个网站,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文件截图:

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

  1. [Python爬虫] 使用 Beautiful Soup 4 快速爬取所需的网页信息

    [Python爬虫] 使用 Beautiful Soup 4 快速爬取所需的网页信息 2018-07-21 23:53:02 larger5 阅读数 4123更多 分类专栏: 网络爬虫   版权声明: ...

  2. Python爬虫教程-13-爬虫使用cookie爬取登录后的页面(人人网)(下)

    Python爬虫教程-13-爬虫使用cookie爬取登录后的页面(下) 自动使用cookie的方法,告别手动拷贝cookie http模块包含一些关于cookie的模块,通过他们我们可以自动的使用co ...

  3. Python爬虫小实践:爬取任意CSDN博客所有文章的文字内容(或可改写为保存其他的元素),间接增加博客访问量

    Python并不是我的主业,当初学Python主要是为了学爬虫,以为自己觉得能够从网上爬东西是一件非常神奇又是一件非常有用的事情,因为我们可以获取一些方面的数据或者其他的东西,反正各有用处. 这两天闲 ...

  4. Python爬虫小白入门(六)爬取披头士乐队历年专辑封面-网易云音乐

    一.前言 前文说过我的设计师小伙伴的设计需求,他想做一个披头士乐队历年专辑的瀑布图. 通过搜索,发现网易云音乐上有比较全的历年专辑信息加配图,图片质量还可以,虽然有大有小. 我的例子怎么都是爬取图片? ...

  5. Python爬虫入门教程: 27270图片爬取

    今天继续爬取一个网站,http://www.27270.com/ent/meinvtupian/ 这个网站具备反爬,so我们下载的代码有些地方处理的也不是很到位,大家重点学习思路,有啥建议可以在评论的 ...

  6. Python爬虫实战(2):爬取京东商品列表

    1,引言 在上一篇<Python爬虫实战:爬取Drupal论坛帖子列表>,爬取了一个用Drupal做的论坛,是静态页面,抓取比较容易,即使直接解析html源文件都可以抓取到需要的内容.相反 ...

  7. Python爬虫入门教程 8-100 蜂鸟网图片爬取之三

    蜂鸟网图片--啰嗦两句 前几天的教程内容量都比较大,今天写一个相对简单的,爬取的还是蜂鸟,依旧采用aiohttp 希望你喜欢 爬取页面https://tu.fengniao.com/15/ 本篇教程还 ...

  8. python爬虫学习之使用BeautifulSoup库爬取开奖网站信息-模块化

    实例需求:运用python语言爬取http://kaijiang.zhcw.com/zhcw/html/ssq/list_1.html这个开奖网站所有的信息,并且保存为txt文件和excel文件. 实 ...

  9. Python爬虫个人记录(三)爬取妹子图

    这此教程可能会比较简洁,具体细节可参考我的第一篇教程: Python爬虫个人记录(一)豆瓣250 Python爬虫个人记录(二)fishc爬虫 一.目的分析 获取煎蛋妹子图并下载 http://jan ...

随机推荐

  1. 【JAVA零基础入门系列】Day4 变量与常量

    这一篇主要讲解Java中的变量,什么是变量,变量的作用以及如何声明,使用变量. 那么什么是变量?对于初学者而言,可以将变量理解为盒子,这些盒子可以用来存放数据,不同类型的数据需要放在对应类型的盒子里. ...

  2. Jquery跨域读取城市天气预报信息

    最新项目中遇到一个问题,页面需要显示一些天气信息,但是部署网站的服务器没连接外网,只有客户端的电脑能连外网,于是想用js去实现这个功能. 刚开始找了一些方法,单独在浏览器中可以使用,但是在项目中运行的 ...

  3. wpf 制作必输项的*标记

    直接引用帮助文档上的话吧,以免下次忘记! AdornedElementPlaceholder 类 .NET Framework 3.5   其他版本   此主题尚未评级 - 评价此主题   更新:20 ...

  4. Qt+VS2015应用程序发布

    本文以Qt 5.9.1+VS2015编译环境为例介绍应用程序发布流程,也适用于Qt+mingw的情况. 1. Qt依赖库 将需要发布的exe(如test.exe),放到单独的目录. 在"开始 ...

  5. cocos2dx - Sqlite简单封装使用

    前言: 一般游戏需要在手机上记录一些简单的信息,用来保存游戏的进度,玩家的分数等.SQLite作为轻量级.跨平台的关系型数据库,相当适合用于游戏数据的存储. 由于没有加密,有安全性问题,数据上还需要自 ...

  6. php 连接mysql数据库以及增删改查

    php 连接数据库 一般是用面向对象的方法,需要先创建一个对象,即造一个连接对象,然后再写sql语句,(增改查删),最后执行sql语句 其中在创建连接对象时 我们用到的是MySQLI  是不区分大小写 ...

  7. spring boot / cloud (十九) 并发消费消息,如何保证入库的数据是最新的?

    spring boot / cloud (十九) 并发消费消息,如何保证入库的数据是最新的? 消息中间件在解决异步处理,模块间解耦和,和高流量场景的削峰,等情况下有着很广泛的应用 . 本文将跟大家一起 ...

  8. 博客发在win10.me

    看到了http://www.win10.me/?page_id=58 说可以把自己的文章投给win10.me 我试试 抱着没有的心态 居然可以 我联系九幽,和他们说我写了很多博客,质量不好,他们说好 ...

  9. win10 uwp 车表盘 径向规

    车表盘就是有刻度的圆盘加上针,这个控件可以直观让用户知道当前的速度或其他 看名字不知道是什么,我就放一张图 使用很简单,在Nuget,Radial Gauge 要使用大神做的,简单,在使用我们需要在N ...

  10. Java 集合框架之set用法

    Java 集合框架之set 一个简单的例子 创建一个Customer类,类中的属性有姓名(name).年龄(age).性别(gender),每个属性分别有get/set 方法.然后创建两个Custom ...