- 浏览: 4846 次
-
文章分类
最新评论
前两天有人私信我,让我爬这个网站,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. #爬取想要的信息
19. bianhao=[]#存储页面编号
20. pageUrl=[]#存储页面链接
21. templist1=bsObj.find("div",{"class":"pg"})
22. for templist2 in templist1.findAll("a",href=re.compile("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 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.
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. #http://bbs.baobeihuijia.com/forum-191-1.html变成http://bbs.baobeihuijia.com,以便组成页面链接
59. siteindex=siteUrl.rfind("/")
60. tempsiteurl=siteUrl[0:siteindex+1]#http://bbs.baobeihuijia.com/
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=re.compile("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形式:
[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.
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. #http://bbs.baobeihuijia.com/forum-191-1.html变成http://bbs.baobeihuijia.com,以便组成帖子链接
60. siteindex=PageUrl.rfind("/")
61. tempsiteurl=PageUrl[0:siteindex+1]#http://bbs.baobeihuijia.com/
62. #print(tempsiteurl)
63. TieziUrl=[]
64. #爬取想要的信息
65. for templist1 in bsObj.findAll("tbody",id=re.compile("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>标签下,所以编写了以下的代码
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.
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(tieziUrl)#登陆两次
20. driver.get(tieziUrl)
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. #html.close()
33. except UnicodeDecodeError as e:
34. print("-----UnicodeDecodeError url",tieziUrl)
35. except urllib.error.URLError as e:
36. print("-----urlError url:",tieziUrl)
37. except socket.timeout as e:
38. print("-----socket timout:",tieziUrl)
39.
40.
41. while(bsObj.find('title').get_text() == "页面重载开启"):
42. print("当前页面不是重加载后的页面,程序会尝试刷新一次到跳转后的页面\n")
43. driver.get(tieziUrl)
44. html=driver.page_source#将浏览器执行后的源代码赋给html
45. bsObj=BeautifulSoup(html,"html.parser")
46. except Exception as e:
47. driver.close() # Close the current window.
48. driver.quit()#关闭chrome浏览器
49. time.sleep(0.5)
50.
51. driver.close() # Close the current window.
52. driver.quit()#关闭chrome浏览器
53.
54.
55. #查找想要的信息
56. templist1=bsObj.find("td",{"class":"t_f"}).ul
57. if templist1==None:#判断是否不包含ul字段,如果不,跳出函数
58. print("当前帖子页面不包含ul字段")
59. return 1
60. mycsv=['NULL','NULL','NULL','NULL','NULL','NULL','NULL','NULL']#初始化提取信息列表
61. for templist2 in templist1.findAll("font",size=re.compile("^([0-9]+)*$")):
62. tempText=templist2.get_text()
63. #print(tempText[0:4])
64. if "宝贝回家编号" in tempText[0:6]:
65. print(tempText)
66. index=tempText.find(":")
67. tempText=tempText[index+1:]
68. #mycsv.append(tempText)
69. if len(tempText)==0:
70. tempText="NULL"
71. mycsv[0]=tempText
72. if "寻亲编号" in tempText[0:6]:
73. print(tempText)
74. index=tempText.find(":")
75. tempText=tempText[index+1:]
76. if len(tempText)==0:
77. tempText="NULL"
78. #mycsv.append(tempText)
79. mycsv[0]=tempText
80. if "登记编号" in tempText[0:6]:
81. print(tempText)
82. index=tempText.find(":")
83. tempText=tempText[index+1:]
84. if len(tempText)==0:
85. tempText="NULL"
86. #mycsv.append(tempText)
87. mycsv[0]=tempText
88. if "姓" in tempText[0:6]:
89. print(tempText)
90. index=tempText.find(":")
91. tempText=tempText[index+1:]
92. #mycsv.append(tempText)
93. mycsv[1]=tempText
94. if"性" in tempText[0:6]:
95. print(tempText)
96. index=tempText.find(":")
97. tempText=tempText[index+1:]
98. #mycsv.append(tempText)
99. mycsv[2]=tempText
100. if "出生日期" in tempText[0:6]:
101. print(tempText)
102. index=tempText.find(":")
103. tempText=tempText[index+1:]
104. #mycsv.append(tempText)
105. mycsv[3]=tempText
106. if "失踪时身高" in tempText[0:6]:
107. print(tempText)
108. index=tempText.find(":")
109. tempText=tempText[index+1:]
110. #mycsv.append(tempText)
111. mycsv[4]=tempText
112. if "失踪时间" in tempText[0:6]:
113. print(tempText)
114. index=tempText.find(":")
115. tempText=tempText[index+1:]
116. #mycsv.append(tempText)
117. mycsv[5]=tempText
118. if "失踪日期" in tempText[0:6]:
119. print(tempText)
120. index=tempText.find(":")
121. tempText=tempText[index+1:]
122. #mycsv.append(tempText)
123. mycsv[5]=tempText
124. if "失踪地点" in tempText[0:6]:
125. print(tempText)
126. index=tempText.find(":")
127. tempText=tempText[index+1:]
128. #mycsv.append(tempText)
129. mycsv[6]=tempText
130. if "是否报案" in tempText[0:6]:
131. print(tempText)
132. index=tempText.find(":")
133. tempText=tempText[index+1:]
134. #mycsv.append(tempText)
135. mycsv[7]=tempText
136. try:
137. 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文件
138. csvfile.flush()#马上将这条数据写入csv文件中
139. finally:
140. print("当前帖子信息写入完成\n")
141. 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.
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/20100101 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':'bbs.baobeihuijia.com',
32.'Referer':'http://bbs.baobeihuijia.com/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': 'bbs.baobeihuijia.com',
37.'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:51.0) Gecko/20100101 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可以上http://http.zhimaruanjian.com/获取
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=re.compile("^([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可以上http://http.zhimaruanjian.com/获取
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. #http://bbs.baobeihuijia.com/forum-191-1.html变成http://bbs.baobeihuijia.com,以便组成页面链接
243. siteindex=siteUrl.rfind("/")
244. tempsiteurl=siteUrl[0:siteindex+1]#http://bbs.baobeihuijia.com/
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=re.compile("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可以上http://http.zhimaruanjian.com/获取
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. #http://bbs.baobeihuijia.com/forum-191-1.html变成http://bbs.baobeihuijia.com,以便组成帖子链接
330. siteindex=PageUrl.rfind("/")
331. tempsiteurl=PageUrl[0:siteindex+1]#http://bbs.baobeihuijia.com/
332. #print(tempsiteurl)
333. TieziUrl=[]
334. #爬取想要的信息
335. for templist1 in bsObj.findAll("tbody",id=re.compile("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("http://bbs.baobeihuijia.com/thread-213126-1-1.html")
349.#GetALLPageUrl("http://bbs.baobeihuijia.com/forum-191-1.html")
350.#GetCurrentPageTieziUrl("http://bbs.baobeihuijia.com/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("https://bbs.baobeihuijia.com/forum-191-1.html")#寻找失踪宝贝
357. #pageurl=GetALLPageUrl("http://bbs.baobeihuijia.com/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文件截图:
这次依然是用第三方爬虫包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. #爬取想要的信息
19. bianhao=[]#存储页面编号
20. pageUrl=[]#存储页面链接
21. templist1=bsObj.find("div",{"class":"pg"})
22. for templist2 in templist1.findAll("a",href=re.compile("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 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.
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. #http://bbs.baobeihuijia.com/forum-191-1.html变成http://bbs.baobeihuijia.com,以便组成页面链接
59. siteindex=siteUrl.rfind("/")
60. tempsiteurl=siteUrl[0:siteindex+1]#http://bbs.baobeihuijia.com/
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=re.compile("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形式:
[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.
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. #http://bbs.baobeihuijia.com/forum-191-1.html变成http://bbs.baobeihuijia.com,以便组成帖子链接
60. siteindex=PageUrl.rfind("/")
61. tempsiteurl=PageUrl[0:siteindex+1]#http://bbs.baobeihuijia.com/
62. #print(tempsiteurl)
63. TieziUrl=[]
64. #爬取想要的信息
65. for templist1 in bsObj.findAll("tbody",id=re.compile("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>标签下,所以编写了以下的代码
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.
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(tieziUrl)#登陆两次
20. driver.get(tieziUrl)
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. #html.close()
33. except UnicodeDecodeError as e:
34. print("-----UnicodeDecodeError url",tieziUrl)
35. except urllib.error.URLError as e:
36. print("-----urlError url:",tieziUrl)
37. except socket.timeout as e:
38. print("-----socket timout:",tieziUrl)
39.
40.
41. while(bsObj.find('title').get_text() == "页面重载开启"):
42. print("当前页面不是重加载后的页面,程序会尝试刷新一次到跳转后的页面\n")
43. driver.get(tieziUrl)
44. html=driver.page_source#将浏览器执行后的源代码赋给html
45. bsObj=BeautifulSoup(html,"html.parser")
46. except Exception as e:
47. driver.close() # Close the current window.
48. driver.quit()#关闭chrome浏览器
49. time.sleep(0.5)
50.
51. driver.close() # Close the current window.
52. driver.quit()#关闭chrome浏览器
53.
54.
55. #查找想要的信息
56. templist1=bsObj.find("td",{"class":"t_f"}).ul
57. if templist1==None:#判断是否不包含ul字段,如果不,跳出函数
58. print("当前帖子页面不包含ul字段")
59. return 1
60. mycsv=['NULL','NULL','NULL','NULL','NULL','NULL','NULL','NULL']#初始化提取信息列表
61. for templist2 in templist1.findAll("font",size=re.compile("^([0-9]+)*$")):
62. tempText=templist2.get_text()
63. #print(tempText[0:4])
64. if "宝贝回家编号" in tempText[0:6]:
65. print(tempText)
66. index=tempText.find(":")
67. tempText=tempText[index+1:]
68. #mycsv.append(tempText)
69. if len(tempText)==0:
70. tempText="NULL"
71. mycsv[0]=tempText
72. if "寻亲编号" in tempText[0:6]:
73. print(tempText)
74. index=tempText.find(":")
75. tempText=tempText[index+1:]
76. if len(tempText)==0:
77. tempText="NULL"
78. #mycsv.append(tempText)
79. mycsv[0]=tempText
80. if "登记编号" in tempText[0:6]:
81. print(tempText)
82. index=tempText.find(":")
83. tempText=tempText[index+1:]
84. if len(tempText)==0:
85. tempText="NULL"
86. #mycsv.append(tempText)
87. mycsv[0]=tempText
88. if "姓" in tempText[0:6]:
89. print(tempText)
90. index=tempText.find(":")
91. tempText=tempText[index+1:]
92. #mycsv.append(tempText)
93. mycsv[1]=tempText
94. if"性" in tempText[0:6]:
95. print(tempText)
96. index=tempText.find(":")
97. tempText=tempText[index+1:]
98. #mycsv.append(tempText)
99. mycsv[2]=tempText
100. if "出生日期" in tempText[0:6]:
101. print(tempText)
102. index=tempText.find(":")
103. tempText=tempText[index+1:]
104. #mycsv.append(tempText)
105. mycsv[3]=tempText
106. if "失踪时身高" in tempText[0:6]:
107. print(tempText)
108. index=tempText.find(":")
109. tempText=tempText[index+1:]
110. #mycsv.append(tempText)
111. mycsv[4]=tempText
112. if "失踪时间" in tempText[0:6]:
113. print(tempText)
114. index=tempText.find(":")
115. tempText=tempText[index+1:]
116. #mycsv.append(tempText)
117. mycsv[5]=tempText
118. if "失踪日期" in tempText[0:6]:
119. print(tempText)
120. index=tempText.find(":")
121. tempText=tempText[index+1:]
122. #mycsv.append(tempText)
123. mycsv[5]=tempText
124. if "失踪地点" in tempText[0:6]:
125. print(tempText)
126. index=tempText.find(":")
127. tempText=tempText[index+1:]
128. #mycsv.append(tempText)
129. mycsv[6]=tempText
130. if "是否报案" in tempText[0:6]:
131. print(tempText)
132. index=tempText.find(":")
133. tempText=tempText[index+1:]
134. #mycsv.append(tempText)
135. mycsv[7]=tempText
136. try:
137. 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文件
138. csvfile.flush()#马上将这条数据写入csv文件中
139. finally:
140. print("当前帖子信息写入完成\n")
141. 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.
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/20100101 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':'bbs.baobeihuijia.com',
32.'Referer':'http://bbs.baobeihuijia.com/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': 'bbs.baobeihuijia.com',
37.'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:51.0) Gecko/20100101 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可以上http://http.zhimaruanjian.com/获取
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=re.compile("^([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可以上http://http.zhimaruanjian.com/获取
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. #http://bbs.baobeihuijia.com/forum-191-1.html变成http://bbs.baobeihuijia.com,以便组成页面链接
243. siteindex=siteUrl.rfind("/")
244. tempsiteurl=siteUrl[0:siteindex+1]#http://bbs.baobeihuijia.com/
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=re.compile("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可以上http://http.zhimaruanjian.com/获取
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. #http://bbs.baobeihuijia.com/forum-191-1.html变成http://bbs.baobeihuijia.com,以便组成帖子链接
330. siteindex=PageUrl.rfind("/")
331. tempsiteurl=PageUrl[0:siteindex+1]#http://bbs.baobeihuijia.com/
332. #print(tempsiteurl)
333. TieziUrl=[]
334. #爬取想要的信息
335. for templist1 in bsObj.findAll("tbody",id=re.compile("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("http://bbs.baobeihuijia.com/thread-213126-1-1.html")
349.#GetALLPageUrl("http://bbs.baobeihuijia.com/forum-191-1.html")
350.#GetCurrentPageTieziUrl("http://bbs.baobeihuijia.com/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("https://bbs.baobeihuijia.com/forum-191-1.html")#寻找失踪宝贝
357. #pageurl=GetALLPageUrl("http://bbs.baobeihuijia.com/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文件截图:
相关推荐
python爬虫,爬取贴吧python爬虫,爬取贴吧python爬虫,爬取贴吧python爬虫,爬取贴吧python爬虫,爬取贴吧python爬虫,爬取贴吧python爬虫,爬取贴吧python爬虫,爬取贴吧python爬虫,爬取贴吧python爬虫,爬取贴吧...
【Python爬虫获取招聘网站信息并保存为CSV文件】 在Python编程中,网络爬虫是一种常用的技术,用于自动化地从互联网上抓取信息。在这个场景中,我们将学习如何使用Python来爬取招聘网站上的职位信息,并将其存储为...
爬取的内容是,衣服(clothing):商品标题(title)、链接(url)、价格(price)、月交易量(monthly_sales)和图片信息(img)。基于网络爬虫技术,爬取淘宝衣服数据。淘宝衣服数据被保存为三种形式(txt形式、...
Python作业:爬虫爬取京东评论;Python作业:爬虫爬取京东评论;Python作业:爬虫爬取京东评论;Python作业:爬虫爬取京东评论;Python作业:爬虫爬取京东评论;Python作业:爬虫爬取京东评论;Python作业:爬虫爬取...
小白学 Python 爬虫(5):前置准备(四)数据库基础 小白学 Python 爬虫(6):前置准备(五)爬虫框架的安装 小白学 Python 爬虫(7):HTTP 基础 小白学 Python 爬虫(8):网页基础 小白学 Python 爬虫(9):...
在实际应用中,我们通常会将爬取到的数据保存到本地文件(如CSV或JSON),或者存入数据库如MySQL或MongoDB,以便后续的数据分析和应用。 总的来说,这个案例涵盖了Python爬虫开发的基本流程,从多线程爬取、HTML...
- 可以使用`pipelines`处理爬取到的数据,如写入CSV、JSON文件,或者存入数据库。 - 定义自己的类继承`ItemPipeline`,重写`process_item()`方法。 6. **Scrapy设置**: - 在`settings.py`中可配置下载延迟、...
Python爬虫入门知识点详细解析: 一、Python爬虫概念与应用 网络爬虫是按照一定的规则,自动抓取互联网信息的程序或脚本。它可以模拟用户浏览网页的行为,对网页内容进行提取、保存。Python爬虫由于其代码简洁、库...
【作品名称】:python爬虫-基于python 实现的爬取人民日报,爬取人民日报文章后存储到本地【课程设计】(课程设计报告+源码) ...文信息后写入到对用的文件中,最后程序结束运行并提示已经爬取完成。
在本Python爬虫案例中,我们将探讨如何使用Python来爬取前程无忧网站的数据。前程无忧(51Job)是中国领先的招聘网站之一,提供大量的职位信息,这为我们提供了丰富的数据源来学习和实践网络爬虫技术。 首先,我们...
Python的pandas库非常方便地实现了这一功能,可以将抓取到的数据结构化并写入Excel文件。在本案例中,我们看到有芒果、草莓、鸭舌帽等商品的数据excel文件,这表明爬虫已经成功运行并保存了结果。 在分析和处理这些...
项目功能:使用Python爬取Top100电影榜单数据并保存csv文件,需要的小伙伴们下载源码做参考即可。 开发工具 Python版本: 3.6 相关模块: requests模块、time模块、parsel模块、csv模块。 操作: 浏览器中打开...
本实战案例涉及使用Python编写一个爬虫程序,用于批量爬取B站(哔哩哔哩)上的小视频。这个案例将使用到requests库来发送HTTP请求,以及BeautifulSoup库来解析网页内容。 适用人群 Python开发者:希望提高网络爬虫...
在本实战案例中,我们将深入探讨如何利用Python爬虫技术来获取并分析互联网上的招聘信息,以腾讯招聘为例。Python作为一款强大的编程语言,其简洁的语法和丰富的库资源使其成为爬虫开发的首选工具。本教程将涵盖以下...
这篇文章给大家通过实例讲解了Python爬取网页数据的步骤以及操作过程,有兴趣的朋友跟着学习下吧。 一、利用webbrowser.open()打开一个网站: >>> import webbrowser >>> webbrowser.open('...
Python网络爬虫是一种用于自动化获取网页数据的技术,它在信息技术领域有着广泛的应用,尤其是在数据分析、信息挖掘和搜索引擎优化等方面。本项目将详细讲解如何利用Python进行网络爬虫的开发,以实现从特定网站抓取...
12. **爬虫伦理与法律法规**:了解并遵守《互联网信息服务管理办法》等相关法律法规,尊重网站的robots.txt文件,避免对网站造成过大负担。 通过这个课程设计,你不仅会掌握Python爬虫技术,还能在实践中提升解决...
《Python爬虫实战:下厨房网站信息爬取详解》 Python爬虫技术是现代数据分析和信息获取的重要工具,尤其在互联网大数据时代,爬虫技术的应用日益广泛。本案例以“下厨房”网站为例,深入讲解如何利用Python进行网页...