#导入模块
from bs4 import BeautifulSoup#数据获取网页解析
import re #正则表达式文字匹配
import urllib.request,urllib.error#制定url获取指定数据
import xlwt#进行excel操作
import sqlite3#数据库包
def main():
baseurl = "https://movie.douban.com/top250?start=0"
datalist = getData(baseurl)#爬取网页
savepath = ".\\豆瓣电影.xls"
# askURL("https://movie.douban.com/top250?start=0")
#影片详情链接的规则
findLink = re.compile(r'<a href="(.*?)">')#创建正则对象表示规则
#影片图片链接
findImgs = re.compile(r'<img.*src="(.*?)"',re.S)
#影片片名链接
findTitle = re.compile(r'<span class="title">(.*)</span> ')
#影片评分
findRating = re.compile(r'<span class="rating_num" property="v:average">(.*)</span>')
#评价人数
findJudge = re.compile(r'<span>(\d*)人评价</span>')#\d数字等价于0-9
#找到概况
findInq = re.compile(r'<span class="inq">(.*)</span>')
#找到影片相关内容
findBd = re.compile(r'<p class=" ">(/p)',re.S)
#爬取网页
def getData(baseurl):
datalist = []
for i in range(0,1):
url = baseurl + str(i * 25)
html = askURL(url)
#逐一解析
soup = BeautifulSoup(html,"html.parser")
#查找符合要求字符串,形成列表
for item in soup.find_all('div',class_="item"):
#print(item)#测试查看电影item
data = []
item = str(item)
#影片详情链接
Link = re.findall(findLink,item)
data.append(Link)
imgsrc = re.findall(findImgs,item)[0]
data.append(imgsrc)#添加图片
titles = re.findall(findTitle,item)#片名只添加中文名
if(len(titles) == 2):
ctitle = titles[0]
data.append(ctitle)
otitle = titles[1].replace("/","")
data.append(otitle)#添加外国名
else:
data.append(titles[0])
data.append(' ')#外国名字留空
rating = re.findall(findJudge,item)[0]
data.append(rating)#添加评分
judgeNum = re.findall(findJudge,item)[0]
data.append(judgeNum)#添加评价人数
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)#去掉<br/>
bd = re.sub('/'," ",bd)#/替换成空值
data.append(bd.strip())#去掉前后空格
datalist.append(data) #处理好的放入datalist
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/91.0.4472.164 Safari/537.36"}
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
#保存数据
def saveData(savepath):
print("save")
if __name__ == "__main__":
main()
|