gpt4 book ai didi

python - 无法在 Excel 文件中正确写入提取的项目?

转载 作者:行者123 更新时间:2023-11-28 22:26:00 26 4
gpt4 key购买 nike

我用 python 编写了一些代码来解析网页的标题和链接。最初,我尝试解析左侧栏中的链接,然后通过跟踪每个链接从每个页面中抓取上述文档。我做得很完美。我试图将不同页面中不同链接的文档保存在一个excel文件中。但是,它创建了几个“工作表”,从我的脚本的标题变量中提取所需的部分作为工作表名称。我面临的问题是——保存数据时,只有链接中每一页的最后一条记录保存在我的 Excel 工作表中,而不是完整记录。这是我试过的脚本:

import requests
from lxml import html
from pyexcel_ods3 import save_data

web_link = "http://www.wiseowl.co.uk/videos/"
main_url = "http://www.wiseowl.co.uk"

def get_links(page):

response = requests.Session().get(page)
tree = html.fromstring(response.text)
data = {}
titles = tree.xpath("//ul[@class='woMenuList']//li[@class='woMenuItem']/a/@href")
for title in titles:
if "author" not in title and "year" not in title:
get_docs(data, main_url + title)

def get_docs(data, url):

response = requests.Session().get(url)
tree = html.fromstring(response.text)

heading = tree.findtext('.//h1[@class="gamma"]')

for item in tree.xpath("//p[@class='woVideoListDefaultSeriesTitle']"):
title = item.findtext('.//a')
link = item.xpath('.//a/@href')[0]
# print(title, link)
data.update({heading.split(" ")[-4]: [[(title)]]})
save_data("mth.ods", data)

if __name__ == '__main__':
get_links(web_link)

最佳答案

当您更新 data 字典中的值时,先前的值将被替换。

如果您替换此行,您可以解决此问题:

data.update({heading.split(" ")[-4]: [[(title)]]})

有了这个(它有点难看,但它有效):

data[heading.split(" ")[-4]] = data.get(heading.split(" ")[-4], []) + [[(title)]]

关于python - 无法在 Excel 文件中正确写入提取的项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45131395/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com