簡體   English   中英

無法在單個csv文件中將抓取的標題寫到四個不同的工作表中

[英]Can't write scraped titles into four different sheets in a single csv file

我編寫了一個腳本,該腳本將來自四個不同站點的抓取標題寫到一個csv文件表中。 如果我想在一個csv文件的四個不同的表中編寫四個不同的標題,是否可以? 到目前為止,這是我嘗試過的:

import csv
import requests
from lxml import html

web_list = ['www.dailynews.com','www.dailynews.co.zw','www.gulf-daily-news.com','www.dailynews.gov.bw'] 
outfile=open("title.csv","w",newline='')
writer=csv.writer(outfile)
for websites in web_list:
    url = "http://" + websites
    page = requests.get(url).text
    tree= html.fromstring(page)
    for site_title in tree.xpath("//title"):
        title=site_title.xpath(".//text()")
    writer.writerow(title)

使用python3(更易於處理unicode)和提到的lib,您可以通過以下方式轉換代碼:

import requests
from lxml import html
from pyexcel_ods3 import save_data

web_list = ['www.dailynews.com','www.dailynews.co.zw','www.gulf-daily-news.com','www.dailynews.gov.bw'] 
outfile=open("title.csv","w",newline='')

data = {}
for i, websites in enumerate(web_list):
    url = "http://" + websites
    page = requests.get(url).text
    tree= html.fromstring(page)
    for site_title in tree.xpath("//title"):
        title=site_title.xpath(".//text()")
        title.remove('\n')
    data.update({"Sheet"+str(i): [[str(title[0])]]})
save_data("your_file.ods", data)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM