2016-10-11 8 views
0

私は以下のコードを持っています。私がやろうとしているのは、ウェブサイトをスクリーンセープし、そのデータをExcelワークシートに書き込むことです。私はExcelファイルから既存のデータを読み取ることができません。pythons xlrdモジュールを使ってExcelシートを読む方法

import xlwt 
import xlrd 
from xlutils.copy import copy 
from datetime import datetime 
import urllib.request 
from bs4 import BeautifulSoup 
import re 
import time 
import os 
links= open('links.txt', encoding='utf-8') 
#excel workbook 
if os.path.isfile('./TestSheet.xls'): 
    rbook=xlrd.open_workbook('TestSheet.xls',formatting_info=True) 
    book=copy(rbook) 
else: 
    book = xlwt.Workbook() 

try: 
    book.add_sheet("wayanad") 
except: 
    print("sheet exists") 
    sheet=book.get_sheet(1) 

for line in links: 
    print("Currently Scanning\n","\n=================\n",line.rstrip()) 
    url=str(line.rstrip())  
    req = urllib.request.Request(url, headers={'User-Agent': 'Mozilla/5.0'}) 
    html = urllib.request.urlopen(req) 
    soup = BeautifulSoup(html,"html.parser") 
    #print(soup.prettify()) 
    title=soup.find('h1').get_text()  
    data=[] 
    for i in soup.find_all('p'): 
     data.append(i.get_text()) 
    quick_descr=data[1].strip() 
    category=data[2].strip() 
    tags=data[3].strip() 
    owner=data[4].strip() 
    website=data[6].strip() 
    full_description=data[7] 
    address=re.sub('\s+', ' ', soup.find('h3').get_text()).strip() 
    city=soup.find(attrs={"itemprop": "addressRegion"}).get_text().strip() 
    postcode=soup.find(attrs={"itemprop": "postalCode"}).get_text().strip() 
    phone=[] 
    result=soup.findAll('h4') 
    for h in result: 
     if h.has_attr('itemprop'): 
      phone.append(re.sub("\D", "", h.get_text())) 

    #writing data to excel 
    row=sheet.last_used_row 
    column_count=sheet.ncols()  
    book.save("Testsheet.xls") 
    time.sleep(2)   

コードが

  • を説明し、私は多くのリンク行ずつがあり、リンクファイルを持っています。したがって、ライン(URL)を選択し、そのURLに行き、データをスクレイプします。
  • Excelブックを開き、データを書き込むためのシートに切り替えます。
  • シートをエクセルにデータを追加.- >> EXECLシート構造の

スクリーンショット enter image description here

現在リストは空です。しかし、私は最後の行から続行したい。 セルからデータを読み取ることができませんでした。 documentation sayssheet.ncolsがあり、列を数えることができます。しかし、それはエラーをスローする

>>>column_count=sheet.ncols() 
>>>AttributeError: 'Worksheet' object has no attribute 'ncols' 

私が望むのは、行と列を数え、セルからデータを読み込む方法です。多くのturialsは古いです。今私はPython 3.4を使用しています。私はすでにこのリンクや他の多くのものを見てきました。しかし、運

Stack overflow

Stackoverdlow

答えて

0

は、あなたが探しているものということではありませんか?すべての列を通過していますか?

xl_workbook = xlrd.open_workbook 

num_cols = xl_sheet.ncols 
for row_idx in range(0, xl_sheet.nrows): 
+0

コードでわかるように、私は「シート」というワークシートを持っています。しかし、 'sheet.nrows'は>>>シートでエラーがこのproperty.'を持っていないスローsheet.nrows トレースバック(最新の呼び出しの最後): sheet.nrows はAttributeErrorで ファイル ""、ライン1、 : 'Worksheet'オブジェクトには属性 'nrows'がありません >>> ' –

+1

最後にこのように私のために働いていました:' xl_workbook = xlrd.open_workbook(r ".xlsx") ' ' sheet_names = xl_workbook.sheet_names() ' 'xl_sheet = xl_workbook.sheet_by_name(sheet_names [0])' – Laura

+0

のrow_idxのためのnum_cols = xl_sheet.ncols' ''答えはあなたのコメントが正しくありませんでした私にその考えを与えた。私がシートからデータを読みたいと思ったら。シートは 'xlrd'オブジェクトでなければなりませんが、私の場合(' sheet'オブジェクト)は 'xlwt'オブジェクトです。ありがとう –

関連する問題