我正在写一个脚本来帮助更新我网站上的一个小博客,但出于某种原因,当我请求页面的HTML,以便我可以将其写入内存并修改它时,它似乎在分隔行:
预期:
<html>
<head>
<!-- <link rel="icon" href="/sort/this/later.jpg" type="image/x-icon" />-->
<title>foo</title>
<meta name="description" content="bar" />
我的脚本收到了什么:
<html>
<head>
<!-- <link rel="icon" href="/sort/this/later.jpg" type="image/x-icon" />-->
<title>foo</title>
<meta name="description" content="bar" />
我尝试从响应中剥离\n
和\r
字符,但这似乎没有任何改变
编辑:对不起,我忘了发布实际的脚本本身。给你:
import neocities
import requests
import re
nc = neocities.NeoCities(api_key='[no]')
response = nc.info()
print(response)
htmlresponse = requests.get('https://thesite.com/index.html')
oldBlog = open('newindex.html', 'w')
oldBlog.write(str(htmlresponse.text).strip('\n').strip('\r'))
oldBlog.close()
with open('newindex.html', 'r') as blog:
contents = blog.readlines()
contents.insert(39,' <p class="header">test lol</p>\n'
' <p class="logpost">foobar</p>\n')
with open('newindex.html', 'w') as blog:
contents = "".join(contents)
blog.write(contents)
我知道我用来脱衣的方法非常简陋,但我只是想看看它是否有效。如果它能起作用,我会把它弄干净
改变
到
假设html是python字符串(在代码中
html_string
是str(htmlresponse.text)
):按换行符
html_string.split('\n')
拆分它将输出:这段代码将提取列表中的每个字符串,如果字符串的长度为
> 0
,则将其保留或更紧凑:
这将给你:
但是
list1
是一个列表。要将其转换回字符串,您需要:打印
new_html_string
将为您提供:总而言之:
相关问题 更多 >
编程相关推荐