豆瓣top250爬虫
请问我这个代码为什么最后print出来的是一个空列表{:10_266:} 我看不出是哪里的问题~import requests
from bs4 import BeautifulSoup
def get_movies():
movie_list = []
headers = {
'user-agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36'
}
for i in range(0,10):
link = 'https://movie.douban.com/top250?start='+str(i*25)
r = requests.get(link,headers = headers,timeout = 10)
print(str(i+1)+'响应状态码:',r.status_code)
soup = BeautifulSoup(r.text,'lxml')
div_list = soup.find_all('div',class_='hd')
for each in div_list:
movie = each.a.span.text.strip()
movie_list.append(movie)
return movie_list
get_movies()
print(movie_list) 函数最后返回了movie_list,所以主程序只要调用get_movies函数并打印就能得到列表。
倒数第二句调用函数,因为函数只返回了movie_list并没有打印,所以没值
倒数第一句是打印了movie_list,但这个movie_list是全局变量,所以报错未定义
所以最后两句改为print(get_movies()),也就是打印函数返回值,即可。
代码如下:
import requests
from bs4 import BeautifulSoup
def get_movies():
movie_list = []
headers = {
'user-agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36'
}
for i in range(0,10):
link = 'https://movie.douban.com/top250?start='+str(i*25)
r = requests.get(link,headers = headers,timeout = 10)
print(str(i+1)+'响应状态码:',r.status_code)
soup = BeautifulSoup(r.text,'lxml')
div_list = soup.find_all('div',class_='hd')
for each in div_list:
movie = each.a.span.text.strip()
movie_list.append(movie)
return movie_list
# get_movies()
# print(movie_list)
print(get_movies())
页:
[1]