未修改,测试,记录第一次写爬虫
#import bs4 #网页解析,获取数据
#import re #正则表达式,进行文字匹配
#import urllib.request,urllib.error #制定url,获取网页数据
#import xlwt #进行excel操作
#import sqlite3 #进行SQLite数据库操作
import urllib.request, urllib.error
from bs4 import BeautifulSoup
import re
import xlwt #进行excel操作
#1.爬取网页
#2.逐一解析数据
#3.保存数据
def main():
baseurl = "https://movie.douban.com/top250?start="
datalist = getData(baseurl)
# 3.保存数据
savepath = "豆瓣电影Top250.xls"
saveData(datalist,savepath)
#askURL("https://movie.douban.com/top250?start=0")
#电影详情字符串匹配规则
findLink = re.compile(r'<a href="(.*?)">')
#图片规则
findImgSrc = re.compile(r'<img.*src="(.*?)"',re.S) #re.S让换行符包含在字符中
#电影名字
findTitle = re.compile(r'<span class="title">(.*)</span>')
#评分
findBating = re.compile(r'<span class="rating_num" property="v:average">(.*)</span>')
#概况
findInq = re.compile(r'<span class="inq">(.*)</span>')
#电影的相关内容
findBd = re.compile(r'<p class="">(.*?)</p>',re.S)
#1.爬取网页
def getData(baseurl):
datalist = []
#10个网页(左闭右开)
for i in range(0,10):
#每一页有25条电影信息
url = baseurl + str(i*25)
html = askURL(url) #保存获取的网页
# 2.逐一解析数据
soup = BeautifulSoup(html,"html.parser")
for item in soup.find_all('div',class_="item"): #查找符号的字符串,形成列表
# print(item)
data = [] #保存电影信息
item = str(item)
#电影详细的链接
link = re.findall(findLink,item)[0]
data.append(link)
imgSrc = re.findall(findImgSrc,item)[0]
data.append(imgSrc)
titles = re.findall(findTitle, item)[0]
data.append(titles)
rating = re.findall(findBating,item)[0]
data.append(rating)
inq = re.findall(findInq,item)
if len(inq) != 0:
inq = inq[0].replace("。","")
data.append(inq)
else:
data.append(" ")
bd = re.findall(findBd,item)[0]
bd = re.sub('<br(\s+)?/>(\s+)?'," ",bd)
bd = re.sub('/'," ",bd)
data.append(bd.strip()) #去掉前后空格
datalist.append(data)
#print(datalist)
return datalist
#得到一个指定的url网页的内容
def askURL(url):
#用户代理,告诉豆瓣访问网页的机器类型
head = {
"User-Agent":"Mozilla / 5.0(Windows NT 10.0; Win64;x64) AppleWebKit / 537.36(KHTML, like Gecko) Chrome / 75.0.3770.100 Safari / 537.36"
} #User-Agent不要有空格
request = urllib.request.Request(url,headers=head)
html=""
try:
response = urllib.request.urlopen(request)
html = response.read().decode("utf-8")
#print(html)
except urllib.error.URLError as e:
if hasattr(e,"code"):
print(e.code)
if hasattr(e, "reason"):
print(e.reason)
return html
#3.保存数据
def saveData(datalist, savepath):
workbook = xlwt.Workbook(encoding="utf-8",style_compression=0)
worksheet = workbook.add_sheet('豆瓣电影Top250',cell_overwrite_ok=True)
col = ("电影详情","图片","名字","评分","概况","相关内容")
for i in range(0,6):
worksheet.write(0,i,col[i]) #列名
for n in range(0,250):
print("dd:%d"%n)
data = datalist[n]
for j in range(0,6):
worksheet.write(n+1,j,data[j])
workbook.save('豆瓣电影Top250.xls')
if __name__ == "__main__": #程序执行时:
#调用函数
main()
print("爬取完毕")