我用python编写了一些代码来解析网页的标题和链接。最初,我试着从左侧栏中解析链接,然后通过跟踪每个链接从每个页面中删除上述文档。我做得很完美。我试图将不同页面中不同链接的文档保存在一个excel文件中。但是,它创建了几个“Sheets”,从脚本的heading变量中提取所需的部分作为sheet name。我面临的问题是-保存数据时,只有链接中每页的最后一条记录保存在我的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
dict中的值时,前面的值将被替换。
如果替换此行,可以修复此问题:
data.update({heading.split(" ")[-4]: [[(title)]]})
有了这个(它有点难看,但很管用):
data[heading.split(" ")[-4]] = data.get(heading.split(" ")[-4], []) + [[(title)]]