簡體   English   中英

如何在python中將html文件作為字符串存儲在變量中

[英]How to store a html file in a variable as a string in python

我有一個 html 文件,我想將該文件的內容作為字符串值存儲在一個變量中。 我試過這個,但它返回一個空字符串。 我該怎么做?

def myfunc():
    str = ""
    with open("/home/suman/Alert_logo_report.html") as report_file:
        raw_html = report_file.readlines()
        str = ''.join(raw_html)
    return str

奇怪,我沒有看到這種行為:

def get_content(path):
    with open(path) as f:
        raw_lines = f.readlines()
    content = ''.join(raw_lines)
    return content

給我 HTML 內容。

另一方面: - 你正在覆蓋str ,它是一個基本的 python 函數,用於轉換字符串中的某些內容。 我不能很好地看到這個結局(意思是:我過去做過,它不漂亮)-不需要聲明變量,這是python-我不明白為什么要讀行,然后加入它們不做任何事情。

在我看來,這會更好:

def get_content(path):
    with open(path) as f:
        raw = f.read()
    return raw

使用"""string_literal"""而不是"string_literal"'string_literal' """string_literal""" 用於多行字符串。 這將起作用。

def myfunc():
str = """"""
with open("employees.html") as report_file:
    raw_html = report_file.readlines()
    str = """""".join(raw_html)
return str

試試這個

f = open("0101.html", "r")
str1 = f.readlines()
print(str1)
f.close()

暫無
暫無

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

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