import requests
from bs4 import BeautifulSoup
import re
#获取html页面信息
def getHTMLText(url):
#模拟用户访问
kv = {‘user-agent’:‘Mozilla/5.0 (Windows NT 10.0; Win64; x64)
AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36’}
try:
r = requests.get(url, timeout = 30, headers = kv)
r.raise_for_status()
r.encoding = r.apparent_encoding
return r.text
except:
return “”
#BeautifulSoup页面解析
def parsePage(lst,html):
html = getHTMLText(url)
try:
soup = BeautifulSoup(html,‘html.paeser’)
movieList = soup.find_all(‘li’)
for movie in movieList:
top = movie.find(‘em’,attrs={‘class’:’’}).getText()
title = movie.find(‘span’,attrs={‘class’:‘title’}).getText()
other = movie.find(‘span’,attrs={‘class’:‘other’}).getText()
directorActor = movie.find(‘p’,attrs={‘class’:’’}).getText()
ratingNum = movie.find(‘span’,attrs={‘class’:‘rating_num’}).getText()
ratingP = movie.find(text = re.compile(‘人评价$’))
inq = movie.find(‘span’,attrs={‘class’:‘inq’})
if not inq:
inq = “暂无”
else:
inq = inq.getText()
lst.append(top + “\t” +title + “\t” +other + “\t” +directorActor + “\t” +ratingP + “\t” +ratingNum + “\t” +inq)
except:
return “”
#存储到本地
def saveMovieInfo(lst,fpath):
with open(“doubanTop250.txt”,“w+”) as f:
f.write("\n".join(lst))
return “”
def main():
depth = 10
start_url = “https://movie.douban.com/top250?start=”
output_file = “C://Users//lenovo//Desktop//Python//scripter//doubanTop250.txt”
infoList = []
for i in range(depth):
try:
url = start_url + str(25*i)
getHTMLText(url)
parsePage(infoList,html)
except:
continue
saveMovieInfo(infoList,output_file)
if name == “main”:
main()
小白求教哪里错了,完全运行不出来