|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
我想爬取这个页面的所有电影名称
代码如下:
import requests
from bs4 import BeautifulSoup
import openpyxl
def open_url(url):
headers = {'user-agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36'
}
html = requests.get(url, headers=headers).text
return html
def get_data(html):
content = BeautifulSoup(html, "html.parser")
data = content.find_all('li', attrs={'class': 'stitle'})
cinema_list = []
for d in data:
plist = d.find('a')['title']
cinema_list.append(plist)
return cinema_list
def save_as_excel(mylist):
wb = openpyxl.Workbook()
ws = wb.active
ws['A1'] = '电影'
for d in mylist:
ws.append([d])
wb.save('2023电影排行.xlsx')
def main():
url = 'https://movie.douban.com/cinema/nowplaying/shanghai/'
html = open_url(url)
mylist = get_data(html)
save_as_excel(mylist)
if __name__ == '__main__':
main()
显示结果只有一个灌篮高手,请问那是为何呢?求大佬帮忙解答一下,谢谢
你的代码中出现了一个小问题。在 get_data 函数中的 for 循环后,需要将 `return cinema_list` 移出循环之外。这是因为当前的代码只会循环到第一个电影名称,然后就直接返回了。
修改后的代码如下所示:
import requests
from bs4 import BeautifulSoup
import openpyxl
def open_url(url):
headers = {'user-agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36'}
html = requests.get(url, headers=headers).text
return html
def get_data(html):
content = BeautifulSoup(html, "html.parser")
data = content.find_all('li', attrs={'class': 'stitle'})
cinema_list = []
for d in data:
plist = d.find('a')['title']
cinema_list.append(plist)
return cinema_list
def save_as_excel(mylist):
wb = openpyxl.Workbook()
ws = wb.active
ws['A1'] = '电影'
for d in mylist:
ws.append([d])
wb.save('2023电影排行.xlsx')
def main():
url = 'https://movie.douban.com/cinema/nowplaying/shanghai/'
html = open_url(url)
mylist = get_data(html)
save_as_excel(mylist)
if __name__ == '__main__':
main()
运行以上代码后,你应该会得到一个电影名称的列表,包含当前正在上映的所有电影名称。
|
|