【问题标题】:Python: How can I save the content of several html files, into a html link, from <title> tag?Python:如何从 <title> 标记将多个 html 文件的内容保存到 html 链接中?
【发布时间】:2021-09-06 20:27:50
【问题描述】:

我有一个 Python 代码,可以很好地解析 html 文件中的一些数据。在代码的末尾,我必须按标签保存 html 文件。例如,我有这 3 个带有 3 个标题标签的 html 文件:

<title>My name is Prince</title>
<title>I love Madonna</title>
<title>Cars and Candies</title>

它们中的每一个都必须像这样保存:

my-name-is-prince.html
I-love-madonna.html
cars-and-candies.html

所以,我已经有了一些 Python 的 SAVE 解决方案,但我不知道如何按标签保存。

try:
    title = re.search('<title.+/title>', html)[0]
    title_content = re.search('>(.+)<', title)[1]
    except:
    pass


with open("my-words.html", "w") as some_file_handle:
    some_file_handle.write(finalString)

with open('page_323.txt', 'w') as f:
    f.write(result.text) 

with open("somefilename.txt", "w") as some_file_handle:  
    for line in data: 
        some_file_handle.write(line + "\n")

附:我有 500 个文件。 Python 代码必须从每个 html 中找到每个标签,并将它们中的每一个保存到新的 html 中。

【问题讨论】:

  • 您是否已经从 html 中提取了标题?

标签: python html tags save-as


【解决方案1】:

更新

你在找那个吗:

# html = """<title>My name is Prince</title>"""

>>> re.search(r'<title>(?P<title>.+)</title>', html).groups('title')[0] \
      .replace(' ', '-').lower()

'my-name-is-prince'

旧答案 如果您已经从 html 中提取标题,您可以这样做:

title = 'My name is Prince'
filename = f"{title.lower().replace(' ', '-')}.html"

with open(filename, "w") as some_file_handle:
    some_file_handle.write(finalString)

【讨论】:

  • 谢谢。是的,是一个不错的选择。问题是我有 500 个文件,无法运行每个文件进行保存。 Python 代码必须从每个 html 中找到每个 标记并将它们中的每一个保存到 html 中。不是一个一个,因为这会花费很多时间。
  • 你使用 BeautifulSoup 吗?你如何解析你的html文件?能否分享更多代码,尤其是在解析数据时?
  • try:title = re.search('&lt;title.+/title&gt;', html)[0]title_content = re.search('&gt;(.+)&lt;', title)[1]except:pass
  • 赞成这个......我认为你不能有一个不写每个文件的解决方案。它不会神奇地发生。你需要使用这样的东西
【解决方案2】:

如果你想使用 beautifulsoup,请检查:

soup = soup.encode(formatter=UnsortedAttributes()).decode('utf-8')
new_filename = title.get_text() 
new_filename = new_filename.lower()
words = re.findall(r'\w+', new_filename)
new_filename = '-'.join(words)
new_filename = new_filename + '.html'
    print(new_filename)

在此处查看完整代码:

https://neculaifantanaru.com/en/python-google-translate-beautifulsoup-library-save-title-tag-as-link.html

【讨论】:

    猜你喜欢
    • 2016-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-30
    • 2013-03-13
    • 1970-01-01
    • 2021-12-02
    相关资源
    最近更新 更多