簡體   English   中英

如何在python中的HTML上打印出函數變量?

[英]How to print out an function variable at HTML in python?

我是一名自學者和初學者,雖然搜索了很多,但可能缺乏搜索。 我正在從兩個網站上抓取一些值,我想將它們與HTML輸出進行比較。 在每個網頁上,我將兩個班級組合在一起,並整理成一個列表。 但是當使用HTML進行輸出時,我不希望所有列表都打印出來。 因此,我使函數可以選擇要打印的任何關鍵字。 當我想打印該功能時,它在HTML輸出上顯示為“ None”,但它變成了我在控制台上想要的內容。 那么如何顯示特殊清單呢?

OS = Windows,Python3。

from bs4 import BeautifulSoup
import requests
import datetime
import os
import webbrowser

carf_meySayf = requests.get('https://www.carrefoursa.com/tr/tr/meyve/c/1015?show=All').text
carf_soup = BeautifulSoup(carf_meySayf, 'lxml')

#spans
carf_name_span = carf_soup.find_all('span', {'class' : 'item-name'})
carf_price_span = carf_soup.find_all('span', {'class' : 'item-price'})


#spans to list
carf_name_list = [span.get_text() for span in carf_name_span]
carf_price_list = [span.get_text() for span in carf_price_span]

#combine lists
carf_mey_all = [carf_name_list +' = ' + carf_price_list for carf_name_list, carf_price_list in zip(carf_name_list, carf_price_list)]



#Function to choose and print special product

def test(namelist,product):
    for i in namelist:
        if product in i:
            print(i)


a = test(carf_mey_all,'Muz')


# Date
date = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")

# HTML part
html_str = """
<html>
    <title>Listeler</title>
        <h2>Tarih: %s</h2>
        <h3>Product & Shop List</h3>
            <table style="width:100%%">
                <tr>
                    <th>Carrefour</th>
                </tr>
                <tr>
                 %s
                </tr>
</html>
""" 

whole = html_str %(date,a)


Html_file= open("Meyve.html","w")
Html_file.write(whole)
Html_file.close()

方法test()必須具有return值,例如

def test(namelist,product):
    results = ''
    for i in namelist:
        if product in i:
            print(i)
            results += '<td>%s</td>\n' % i
    return results

Meyve.html結果:

<html>
<title>Listeler</title>
<h2>Tarih: 2018-12-29 07:34:00</h2>
<h3>Product & Shop List</h3>
<table style="width:100%">
  <tr>
    <th>Carrefour</th>
  </tr>
  <tr>
    <td>Muz = 6,99 TL</td>
    <td>İthal Muz = 12,90 TL</td>
    <td>Paket Yerli Muz = 9,99 TL</td>
  </tr>

</html>

注意:要成為有效的html,您需要添加<body></body>

問題在於您的test()函數沒有顯式返回任何內容,因此它隱式返回了None
為了解決這個問題, test()應該累積要返回的文本(即,通過構建列表或字符串),並返回包含要插入到html_str的文本的字符串。

暫無
暫無

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

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