导出到Excel时数据将覆盖

时间:2019-01-09 12:05:31

标签: python xlwt

我正在抓捕一个网站,以根据一些关键字收集最近的十篇文章。一旦获得数据(使用的关键字,文章名称,URL /超链接和发布日期),我便要将其全部写入xls文件。到目前为止,它只写入最后一个关键字而不是全部四个关键字的结果,只是覆盖了电子表格的同一部分。如何显示我的整个列表,而不仅仅是最近的部分?

def test_old(ldap_con):
    run_test_to_default_connection(ldap_con)


@pytest.mark.parametrize('ldap_con', ['mynewserver'], indirect=True)
def test_new(ldap_con):
    run_test_to_new_connection(ldap_con)

我希望看到我的整个列表,其中会列出所有四个关键字的结果。但是,我只看到最后一个关键字的结果。

1 个答案:

答案 0 :(得分:1)

我已经将Excel文件的生成移到了脚本的末尾:

import requests
from bs4 import BeautifulSoup
import datetime
import xlwt
from xlwt import Formula


today = datetime.date.today().strftime("%Y%m%d")

keywords = ('PNC', 'Huntington', 'KeyCorp', 'Fifth Third')

for keyword in keywords:
    keyword.replace("+", " ")

headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64)       AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36'}


def article_fetch(keyword):
    url = 'https://www.americanbanker.com/search?query={}'.format(keyword)
    r = requests.get(url, headers = headers)

    soup = BeautifulSoup(r.text, 'html.parser')

    for articles in soup.find_all("div", "feed-item"):
        article = articles.find("h4").text.strip()
        timestamp = articles.find("span", "timestamp").text.strip()
        article_url = 'https://{}'.format(articles.find("a")["href"][2:])
        link = 'HYPERLINK("{}", "Link" )'.format(article_url)
        item = [keyword, article, Formula(link), timestamp]
        mylist.append(item)


mylist = []
cols = "KeyWord", "Article", "URL", "Publication Date"
mylist.append(cols)
for keyword in keywords:
    article_fetch(keyword)

book = xlwt.Workbook()
sheet = book.add_sheet('Articles')
for i, row in enumerate(mylist):
    for j, col in enumerate(row):
        sheet.write(i, j, col)
book.save("American Banker {}.xls".format(today))

print('Workbook Saved')

数据不会再丢失:

enter image description here