将网站标题放入Excel电子表格

2024-06-26 14:13:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用BeautifulSoup获取一个网站标题列表,并将它们放入Excel电子表格中。在

文本文件“c:\网站.txt“包含以下内容:

www.dailynews.com
www.dailynews.lk
www.dailynews.co.zw
www.gulf-daily-news.com
www.dailynews.gov.bw

训练计划:

^{pr2}$

它工作良好,并生成网站标题。但是,当我添加以下内容时:

    book = xlwt.Workbook(encoding='utf-8', style_compression = 0)
    sheet = book.add_sheet('Sheet1', cell_overwrite_ok = True)

    for cor, lmn in enumerate(line_in_list):

        sheet.write (cor, 0, site_title)

book.save("C:\\site_titles.xls")

试图让他们一个接一个地把数据输入到Excel电子表格的A列中,这是行不通的。在


Tags: incom标题列表网站wwwsiteexcel
1条回答
网友
1楼 · 发布于 2024-06-26 14:13:30

错误是您试图保存一个BeautifulSoup对象

Exception: Unexpected data type <class 'bs4.element.Tag'>

试着写那个对象的文本值,文件就会写得很好

^{pr2}$


写循环错误,请这样尝试: 最终脚本:

from bs4 import BeautifulSoup
import urllib2
import xlwt

line_in_list = ['www.dailynews.com','www.elpais.com'] #get urls from file
book = xlwt.Workbook(encoding='utf-8', style_compression = 0)
sheet = book.add_sheet('Sheet1', cell_overwrite_ok = True)

for cor,websites in enumerate(line_in_list):
    url = "http://" + websites
    page = urllib2.urlopen(url)
    soup = BeautifulSoup(page.read())
    site_title = soup.find_all("title")
    print site_title
    sheet.write (cor, 0, site_title[0].text)

book.save("site_titles.xls")

相关问题 更多 >