|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
import requests
import bs4
def open_url(url):
headers = {"User-Agent":
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.182 Safari/537.36 Edg/88.0.705.81"}
res = requests.get(url,headers = headers)
return res
def find_movies(res):
soup = bs4.BeautifulSoup(res.text, "html.parser")
#电影名
movies = []
targets = soup.find_all("div", class_="hd")
for each in targets:
movies.append(each.a.span.text)
#评分
ranks =[]
targets = soup.find_all("span", class_="rating_num")
for each in targets:
ranks.append(' 评分: %s ' % each.text)
#资料
messages = []
targets = soup.find_all("span", class_="inq") #没有完全按提示来操作
for each in targets:
messages.append(each.text)
result = []
length = len(movies)
for i in range(length):
result.append(movies[i] + ranks[i] + messages[i] +'\n')
return result
#找出一共有多少个页面
def find_depth(res):
soup = bs4.BeautifulSoup(res.text,'html.parser')
depth =soup.find('span',class_='next').previous_sibling.previous_sibling.text
return int(depth)
def main():
host = 'https://movie.douban.com/top250'
res = open_url(host)
depth = find_depth(res)
result = []
for ix in range(depth):
url = f"{host}?start={25 * ix}&filter=" #这里IX的取值范围不对,depth等于10,但是ix的范围是0-7,不知道应该怎么改
res = open_url(url)
result.extend(find_movies(res))
with open("豆瓣TOP250电影.txt",'w',encoding='utf-8') as f:
for each in result:
f.write(each)
if __name__ == '__main__':
main()
#url = 'https://movie.douban.com/top250'
#print(find_movies(open_url(url)))
#print(find_depth(open_url(url)))
以下图片是错误提示:
错误要一层一层的排查
表面现象是列表索引超范围,实则是空列表
列表为何是空,需要上一级别查找
|
-
|