конвертировать HTML-тег в Excel в Python 3.7 - PullRequest
0 голосов
/ 03 февраля 2019

Я новичок в Python, и я пытаюсь прочитать мою карту сайта.проблема в том, что когда я пытаюсь получить некоторые данные - я получаю ошибки по каждому URL-адресу .. в основном, я хочу прочитать все URL-адреса из моей карты сайта, а затем - я хочу сохранить в Excel все мета и данные, которые мне нужны: title, meta, sku, price и т. д. Я получаю ошибку в моем def get_title -im sendig url, но я не могу добраться до url, в чем проблема с моим кодом?

import requests
from bs4 import BeautifulSoup
from argparse import ArgumentParser
from openpyxl import Workbook
import os

# ** sitemap parsing function **
def parse_sitemap ( url ):
 resp = requests.get ( 'https://www.cdsoft.co.il/kbseowizard/sitemap_1_he.xml' )

# we didn't get a valid response, bail
if 200 != resp.status_code:
    return False

# BeautifulStoneSoup to parse the document
soup = BeautifulSoup ( resp.content, 'xml' )
# find all the <url> tags in the document
urls = soup.findAll ( 'url' )

# no urls? bail
if not urls:
    return False
# storage for later...
out = [ ]
# extract what we need from the url
for u in urls:
    loc = u.find ( 'loc' ).string
    # not a sitemap requirement skip if not present
    out.append ( [ loc ] )

return out


def get_title ( u ):
html = requests.get ( u )
bsObj = BeautifulSoup ( html.read ( ), features='lxml' )
title = str ( bsObj.title ).replace ( '<title>', '' ).replace ( '</title>', '' )
return title

if __name__ == '__main__':
options = ArgumentParser ( )
options.add_argument ( '-u', '--url', action='store', dest='url', help='The file contain one url per line' )
options.add_argument ( '-o', '--output', action='store', dest='out', default='out.txt',
                       help='Where you would like to save the data' )
args = options.parse_args ( )
urls = parse_sitemap ( args.url )
urlFile = open ( "urlFile.txt", "w+" )

# open preparing new excel file
os.chdir ( "/Users/CDsoft/PycharmProjects/dvir/outputs" )
wb = Workbook ( )
ws1 = wb.create_sheet ( 'data', 0 )
ws1 = wb.active

with open ( args.out, 'w' ) as out:
    i = 1

    for u in urls:
        i = i + 1
        u = str ( u )
        title = get_title ( u )
        u = u.split ( ',', 1 ) [ 0 ].rsplit ( "'", 1 ) [ 0 ]
        u = u.replace ( "['", '' )
        urlFile.write ( u + "\n" )
        ws1 [ 'A1' ] = u
        title = get_title ( u )
        ws1 [ 'B1' ] = title
        ws1.insert_rows ( 1 )
        ws1.append ( [ ] )
        if (i > 10):
            break

wb.save ( "sample.xlsx" )
wb.close ( )
   print ( 'end' )
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...