如何存取爬取的数据,万分感谢~~~
我现在想把数据保存在excel表格中,但是报错了,麻烦大佬帮忙解答一下,谢谢~~~代码如下:
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()
报错信息:
E:\anaconda3\python.exe C:/Users/lyl/PycharmProjects/pythonProject1/dangdang/dangdang/spiders/abc.py
Traceback (most recent call last):
File "C:/Users/lyl/PycharmProjects/pythonProject1/dangdang/dangdang/spiders/abc.py", line 1719, in <module>
main()
File "C:/Users/lyl/PycharmProjects/pythonProject1/dangdang/dangdang/spiders/abc.py", line 1716, in main
save_as_excel(mylist)
File "C:/Users/lyl/PycharmProjects/pythonProject1/dangdang/dangdang/spiders/abc.py", line 1708, in save_as_excel
ws.append(d)
File "E:\anaconda3\lib\site-packages\openpyxl\worksheet\worksheet.py", line 675, in append
self._invalid_row(iterable)
File "E:\anaconda3\lib\site-packages\openpyxl\worksheet\worksheet.py", line 811, in _invalid_row
raise TypeError('Value must be a list, tuple, range or generator, or a dict. Supplied value is {0}'.format(
TypeError: Value must be a list, tuple, range or generator, or a dict. Supplied value is <class 'str'>
Process finished with exit code 1
TypeError: Value must be a list, tuple, range or generator, or a dict. Supplied value is <class 'str'>
value 必须是一个列表 元组 区域 或者生成器 或者一个字典 然而你给出的是str wp231957 发表于 2023-4-20 15:51
TypeError: Value must be a list, tuple, range or generator, or a dict. Supplied value is
value 必 ...
那请问该如何修改呢?python小白求指教一下 报错信息提示:在使用`ws.append()`方法时,传入的值必须是列表、元组、范围或生成器,或者是字典。但是你传入的值是一个字符串。为了解决这个问题,你需要将字符串放入一个列表中。修改`save_as_excel`函数如下:
def save_as_excel(mylist):
wb = openpyxl.Workbook()
ws = wb.active
ws['A1'] = '电影'
for d in mylist:
ws.append()# 将 d 放入一个列表中
wb.save('2023电影排行.xlsx')
现在你的代码应该可以正常运行并将数据保存到Excel表格中。 isdkz 发表于 2023-4-21 14:21
报错信息提示:在使用`ws.append()`方法时,传入的值必须是列表、元组、范围或生成器,或者是字典。但是你 ...
谢谢大佬~~~
页:
[1]