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

标签 python excel xpath web-scraping lxml

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

相关文章:

python - MAP 的意外结果

excel - 通过 INDEX MATCH 随机的另一个表的表头名称

xml - 给定一系列XML路径,生成XML树结构

java - 如何将 excel 文件中的字符串分解为子字符串并加载它?

excel - 未触发 VBA 组合框更改事件

php - 使用 SimpleXML 获取第一个 XML 元素

java - 使用 XML 标记在 Saxonica 中检索 XPath 结果

python - 如何迭代数据框以将字典解压到新的数据框中

python - 一个接受字符串和字符并切片直到(包括)第一次出现的字符的函数?

Python 生成 max of mins key 时出错