我用 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/