如何在python中的HTML上打印出函数变量?

时间:2018-12-29 06:40:24

标签: python web-scraping beautifulsoup

我是一名自学者和初学者,虽然搜索了很多内容,但可能缺乏搜索能力。我正在从两个网站上抓取一些值,我想将它们与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()

2 个答案:

答案 0 :(得分:1)

方法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>

答案 1 :(得分:0)

问题在于您的test()函数没有显式返回任何内容,因此它隐式返回了None
为了解决这个问题,test()应该累积要返回的文本(即,通过构建列表或字符串),并返回包含要插入到html_str中的文本的字符串。