python web crawling(4)

web crawling examples with python using urllib,beautifulsoup,re,requests,

doubanbookSpider using python3.6

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
#-*- coding: UTF-8 -*-
import time
import urllib
import urllib.parse
import re
import numpy as np
from bs4 import BeautifulSoup
from openpyxl import Workbook
import importlib,sys
importlib.reload(sys)
#Some User Agents
hds=[{'User-Agent':'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6'},\
{'User-Agent':'Mozilla/5.0 (Windows NT 6.2) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.12 Safari/535.11'},\
{'User-Agent': 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)'}]
def book_spider(book_tag):
page_num=0;
book_list=[]
try_times=0
while page_num<3:
#url='http://www.douban.com/tag/%E5%B0%8F%E8%AF%B4/book?start=0' # For Test
url='http://book.douban.com/tag/'+urllib.parse.quote(book_tag)+'/?start='+str(page_num*20)+'&type=T'
time.sleep(np.random.rand()*5)
#Last Version
try:
req = urllib.request.Request(url, headers=hds[page_num%len(hds)])
source_code = urllib.request.urlopen(req).read()
plain_text=source_code.decode('utf-8')
except (urllib.HTTPError, urllib.URLError) as e:
print (e)
continue
##Previous Version, IP is easy to be Forbidden
#source_code = requests.get(url)
#plain_text = source_code.text
soup = BeautifulSoup(plain_text,"lxml")
list_soup = soup.find('ul', {'class': 'subject-list'})
try_times+=1;
if list_soup==None and try_times<200:
continue
elif list_soup==None or len(list_soup)<=1:
break # Break when no informatoin got after 200 times requesting
for book_info in list_soup.find_all('li',{'class':'subject-item'}):
title = book_info.find("h2")
titlee = title.a['title']
desc = book_info.find('div', {'class':'pub'}).get_text().strip()
desc_list = desc.split('/')
#book_url = book_info.find('a', {'class':'title'}).get('href')
try:
author_info = '作者/译者: ' + '/'.join(desc_list[0:-3])
except:
author_info ='作者/译者: 暂无'
try:
pub_info = '出版信息: ' + '/'.join(desc_list[-3:])
except:
pub_info = '出版信息: 暂无'
try:
rating = book_info.find('span', {'class':'rating_nums'}).get_text().strip()
except:
rating='0.0'
try:
people_num = book_info.find('span',{'class':'pl'}).string.strip()
people_num = re.sub("\D", "",people_num)
#people_num = people_num.strip(u'人评价')
#people_num = get_people_num(book_url)
except:
people_num ='0'
book_list.append([titlee,rating,people_num,author_info,pub_info])
try_times=0 #set 0 when got valid information
page_num+=1
print ('Downloading Information From Page %d' % page_num)
if page_num>3:
break
return book_list
def get_people_num(url):
#url='http://book.douban.com/subject/6082808/?from=tag_all' # For Test
try:
req = urllib.request.Request(url, headers=hds[np.random.randint(0,len(hds))])
source_code = urllib.request.urlopen(req).read()
plain_text=source_code.decode('utf-8')
except (urllib.HTTPError, urllib.URLError) as e:
print (e)
soup = BeautifulSoup(plain_text.decode("utf-8"),"lxml")
people_num=soup.find('div',{'class':'rating_sum'}).find_all('span')[1].string.strip()
return people_num
def do_spider(book_tag_lists):
book_lists=[]
for book_tag in book_tag_lists:
book_list=book_spider(book_tag)
book_list=sorted(book_list,key=lambda x:x[1],reverse=True)
book_lists.append(book_list)
return book_lists
def print_book_lists_excel(book_lists,book_tag_lists):
wb = Workbook()
ws=[]
for i in range(len(book_tag_lists)):
ws.append(wb.create_sheet(title=book_tag_lists[i]))
for i in range(len(book_tag_lists)):
ws[i].append(['序号','书名','评分','评价人数','作者','出版社'])
count=1
for bl in book_lists[i]:
ws[i].append([count,bl[0],float(bl[1]),int(bl[2]),bl[3],bl[4]])
count+=1
save_path='book_list'
for i in range(len(book_tag_lists)):
save_path+=('-'+book_tag_lists[i])
save_path+='.xlsx'
wb.save(save_path)
if __name__=='__main__':
#book_tag_lists = ['心理','判断与决策','算法','数据结构','经济','历史']
#book_tag_lists = ['传记','哲学','编程','创业','理财','社会学','佛教']
#book_tag_lists = ['思想','科技','科学','web','股票','爱情','两性']
#book_tag_lists = ['计算机','机器学习','linux','android','数据库','互联网']
book_tag_lists = ['数学']
#book_tag_lists = ['摄影','设计','音乐','旅行','教育','成长','情感','育儿','健康','养生']
#book_tag_lists = ['商业','理财','管理']
#book_tag_lists = ['名著']
#book_tag_lists = ['科普','经典','生活','心灵','文学']
#book_tag_lists = ['科幻','思维','金融']
#book_tag_lists = ['个人管理','时间管理','投资','文化','宗教']
book_lists=do_spider(book_tag_lists)
print_book_lists_excel(book_lists,book_tag_lists)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
import time
import urllib
import urllib.parse
import requests
import numpy as np
from bs4 import BeautifulSoup
from openpyxl import Workbook
import importlib,sys
importlib.reload(sys)
#Some User Agents
hds=[{'User-Agent':'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6'},\
{'User-Agent':'Mozilla/5.0 (Windows NT 6.2) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.12 Safari/535.11'},\
{'User-Agent': 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)'}]
def book_spider(book_tag):
page_num=0;
book_list=[]
try_times=0
while(1):
#url='http://www.douban.com/tag/%E5%B0%8F%E8%AF%B4/book?start=0' # For Test
url='http://www.douban.com/tag/'+urllib.parse.quote(book_tag)+'/book?start='+str(page_num*15)
time.sleep(np.random.rand()*5)
#Last Version
try:
req = urllib2.Request(url, headers=hds[page_num%len(hds)])
source_code = urllib2.urlopen(req).read()
plain_text=source_code.decode('utf-8')
except (urllib2.HTTPError, urllib2.URLError) as e:
print e
continue
##Previous Version, IP is easy to be Forbidden
#source_code = requests.get(url)
#plain_text = source_code.text
soup = BeautifulSoup(plain_text)
list_soup = soup.find('div', {'class': 'mod book-list'})
try_times+=1;
if list_soup==None and try_times<200:
continue
elif list_soup==None or len(list_soup)<=1:
break # Break when no informatoin got after 200 times requesting
for book_info in list_soup.findAll('dd'):
title = book_info.find('a', {'class':'title'}).string.strip()
desc = book_info.find('div', {'class':'desc'}).string.strip()
desc_list = desc.split('/')
book_url = book_info.find('a', {'class':'title'}).get('href')
try:
author_info = '作者/译者: ' + '/'.join(desc_list[0:-3])
except:
author_info ='作者/译者: 暂无'
try:
pub_info = '出版信息: ' + '/'.join(desc_list[-3:])
except:
pub_info = '出版信息: 暂无'
try:
rating = book_info.find('span', {'class':'rating_nums'}).string.strip()
except:
rating='0.0'
try:
#people_num = book_info.findAll('span')[2].string.strip()
people_num = get_people_num(book_url)
people_num = people_num.strip('人评价')
except:
people_num ='0'
book_list.append([title,rating,people_num,author_info,pub_info])
try_times=0 #set 0 when got valid information
page_num+=1
print 'Downloading Information From Page %d' % page_num
return book_list
def get_people_num(url):
#url='http://book.douban.com/subject/6082808/?from=tag_all' # For Test
try:
req = urllib.request.Request(url, headers=hds[np.random.randint(0,len(hds))])
source_code = urllib.request.urlopen(req).read()
plain_text=source_code.decode('utf-8')
except (urllib2.HTTPError, urllib.URLError) as e:
print e
soup = BeautifulSoup(plain_text)
people_num=soup.find('div',{'class':'rating_sum'}).findAll('span')[1].string.strip()
return people_num
def do_spider(book_tag_lists):
book_lists=[]
for book_tag in book_tag_lists:
book_list=book_spider(book_tag)
book_list=sorted(book_list,key=lambda x:x[1],reverse=True)
book_lists.append(book_list)
return book_lists
def print_book_lists_excel(book_lists,book_tag_lists):
wb=Workbook(optimized_write=True)
ws=[]
for i in range(len(book_tag_lists)):
ws.append(wb.create_sheet(title=book_tag_lists[i])) #utf8->unicode
for i in range(len(book_tag_lists)):
ws[i].append(['序号','书名','评分','评价人数','作者','出版社'])
count=1
for bl in book_lists[i]:
ws[i].append([count,bl[0],float(bl[1]),int(bl[2]),bl[3],bl[4]])
count+=1
save_path='book_list'
for i in range(len(book_tag_lists)):
save_path+=('-'+book_tag_lists[i])
save_path+='.xlsx'
wb.save(save_path)
if __name__=='__main__':
#book_tag_lists = ['心理','判断与决策','算法','数据结构','经济','历史']
#book_tag_lists = ['传记','哲学','编程','创业','理财','社会学','佛教']
#book_tag_lists = ['思想','科技','科学','web','股票','爱情','两性']
#book_tag_lists = ['计算机','机器学习','linux','android','数据库','互联网']
#book_tag_lists = ['数学']
#book_tag_lists = ['摄影','设计','音乐','旅行','教育','成长','情感','育儿','健康','养生']
#book_tag_lists = ['商业','理财','管理']
#book_tag_lists = ['名著']
#book_tag_lists = ['科普','经典','生活','心灵','文学']
#book_tag_lists = ['科幻','思维','金融']
book_tag_lists = ['个人管理','时间管理','投资','文化','宗教']
book_lists=do_spider(book_tag_lists)
print_book_lists_excel(book_lists,book_tag_lists)

doubanmovietagspider

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# coding=utf-8
import urllib
import urllib.parse
from bs4 import BeautifulSoup
headers = {'User-Agent':"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/22.0.1207.1 Safari/537.1"}
num=0
idnum=[]
book_tag_lists = ['文艺']
book_tag = book_tag_lists[num]
while num<1:
url='https://movie.douban.com/tag/'+urllib.parse.quote(book_tag)+'/?start='+str(num*20)+'&type=T'
req = urllib.request.Request(url, headers=headers)
source_code = urllib.request.urlopen(req).read()
plain_text=source_code.decode('utf-8')
soup = BeautifulSoup(plain_text,"lxml")
list_soup = soup.find('div', {'class': 'article'})
for book_info in list_soup.find_all('tr',{'class':'item'}):
title = book_info.find('a',{'class':'nbg'})['title']
idn = book_info.find('a',{'class':'nbg'})['href']
desc = book_info.find('p', {'class':'pl'}).get_text().strip()
desc_list = desc.split('/')
year_info = '' + ''.join(desc_list[0])
rating = book_info.find('span', {'class':'rating_nums'}).get_text().strip()
people_num = book_info.find('span',{'class':'pl'}).string.strip()
idnum.append([idn,title,rating,people_num,year_info])
num=num+1
if num>1:
break
print(idnum)

doubanapispider

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import requests
import json
import time
import csv
headers = {'User-Agent':"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/22.0.1207.1 Safari/537.1"}
with open('23.csv','r') as csvfilea:
reader = csv.reader(csvfilea)
t = [row[0] for row in reader]
csvfilea.close()
s =t
i=550
print(len(s))
idnum=[]
while i<600:
time.sleep(4)
all_url = 'https://api.douban.com/v2/movie/subject/'+s[i]
start_html = requests.get(all_url, headers=headers)
htmlcontent=start_html.content.decode('utf-8')
data = json.loads(htmlcontent.strip())
i=i+1
idn={}
try:
idn['id'] = data['id']
idn['title'] = data['title']
idn['score'] = data['rating']['average']
idn['vote'] = data['ratings_count']
idn['regions'] = data['countries'][0]
idn['date'] = data['year']
idn['types'] = data['genres'][0]
except:
idn['id'] = 'none'
idn['title'] = 'none'
idn['score'] = 'none'
idn['vote'] = 'none'
idn['regions'] = 'none'
idn['date'] = 'none'
idn['types'] = 'none'
idnum.append(idn)
if i> 600:
break
csvfile = open('14.csv', 'w+',newline='')
keys=idnum[0].keys()
writer = csv.writer(csvfile)
writer.writerow(keys)#将属性列表写入csv中
for row in idnum:
writer.writerow(row.values())
csvfile.close()

doubanmoviechartspider

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# coding=utf-8
import requests
import json
import time
import csv
headers = {'User-Agent':"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/22.0.1207.1 Safari/537.1"}
num=0
idnum=[]
while num < 60 :
time.sleep(5)
all_url = 'https://movie.douban.com/j/chart/top_list?type=4&interval_id=80%3A70&action=&start='+str(num)+'&limit=20'
start_html = requests.get(all_url, headers=headers)
htmlcontent=start_html.content.decode('utf-8')
data = json.loads(htmlcontent.strip())
num= num + 20
i=0
while i<20:
idn={}
try:
idn['id'] = data[i]['id']
idn['title'] = data[i]['title']
idn['score'] = data[i]['score']
idn['vote'] = data[i]['vote_count']
idn['regions'] = data[i]['regions'][0]
idn['date'] = data[i]['release_date']
idn['types'] = data[i]['types'][0]
except:
idn['id'] = 'none'
idn['title'] = 'none'
idn['score'] = 'none'
idn['vote'] = 'none'
idn['regions'] = 'none'
idn['date'] = 'none'
idn['types'] = 'none'
idnum.append(idn)
i=i+1
if i>20:
break
if num> 60:
break
csvfile = open('18.csv', 'w+',newline='')
keys=idnum[0].keys()
writer = csv.writer(csvfile)
writer.writerow(keys)#将属性列表写入csv中
for row in idnum:
writer.writerow(row.values())
csvfile.close()