import requests from bs4 import BeautifulSoup import xlwt title_list = [] datalist = [] headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36 Edg/114.0.1823.67" } # 获取网页信息 response = requests.get("https://movie.douban.com/top250", headers=headers) content = response.text soup = BeautifulSoup(content, "html.parser") all_titles = soup.findAll("span", attrs={"class": "title"}) for title in all_titles: title_string = title.string if "/" not in title_string: print(title_string.string) title_list.append(title_string.string) all_comments = soup.findAll("span", attrs={"class": "inq"}) for comment in all_comments: print(comment.string)能不能帮我将title.string和comment.string的数据写入excel文件
时间: 2024-04-19 14:29:08 浏览: 168
当然可以帮您将`title.string`和`comment.string`的数据写入Excel文件。您可以使用`xlwt`库来完成这个任务。以下是示例代码:
```python
import requests
from bs4 import BeautifulSoup
import xlwt
title_list = []
comment_list = []
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36 Edg/114.0.1823.67"
}
# 获取网页信息
response = requests.get("https://movie.douban.com/top250", headers=headers)
content = response.text
soup = BeautifulSoup(content, "html.parser")
all_titles = soup.findAll("span", attrs={"class": "title"})
for title in all_titles:
title_string = title.string
if "/" not in title_string:
title_list.append(title_string)
all_comments = soup.findAll("span", attrs={"class": "inq"})
for comment in all_comments:
comment_list.append(comment.string)
# 创建Excel文件和工作表
workbook = xlwt.Workbook()
worksheet = workbook.add_sheet("Movie Comments")
# 写入数据到Excel文件
for i in range(len(title_list)):
worksheet.write(i, 0, title_list[i])
worksheet.write(i, 1, comment_list[i])
# 保存Excel文件
workbook.save("movie_comments.xls")
```
运行上述代码后,将会在当前目录下生成一个名为`movie_comments.xls`的Excel文件,其中包含了电影标题和评论内容的数据。
阅读全文