Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/287.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/76.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python中删除HTML响应中的行之间的空格_Python_Html_Httpresponse - Fatal编程技术网

在Python中删除HTML响应中的行之间的空格

在Python中删除HTML响应中的行之间的空格,python,html,httpresponse,Python,Html,Httpresponse,我正在写一个脚本来帮助更新我网站上的一个小博客,但出于某种原因,当我请求页面的HTML,以便我可以将其写入内存并修改它时,它似乎在分隔行: 预期: 福 我的脚本收到了什么: 福 我尝试从响应中剥离\n和\r字符,但这似乎没有任何改变 编辑:对不起,我忘了发布实际的脚本本身。给你: 导入新城市 导入请求 进口稀土 nc=新城市。新城市(api_键=“[no]”) 响应=nc.info() 打印(答复) htmlresponse=requests.get('https://thesite.c

我正在写一个脚本来帮助更新我网站上的一个小博客,但出于某种原因,当我请求页面的HTML,以便我可以将其写入内存并修改它时,它似乎在分隔行:

预期:

我的脚本收到了什么:

我尝试从响应中剥离
\n
\r
字符,但这似乎没有任何改变

编辑:对不起,我忘了发布实际的脚本本身。给你:

导入新城市
导入请求
进口稀土
nc=新城市。新城市(api_键=“[no]”)
响应=nc.info()
打印(答复)
htmlresponse=requests.get('https://thesite.com/index.html')
oldBlog=open('newindex.html','w')
oldBlog.write(str(htmlresponse.text).strip('\n').strip('\r'))
oldBlog.close()
以open('newindex.html','r')作为博客:
contents=blog.readlines()
内容。插入(39,

测试lol

\n' “

foobar

\n” 以open('newindex.html','w')作为博客: contents=”“.join(内容) blog.write(内容)
我知道我用来脱衣的方法非常简陋,但我只是想看看它是否有效。如果它能工作,我会把它弄干净。

改变

oldBlog.write(str(htmlresponse.text).strip('\n').strip('\r'))


假设您的html是python字符串(在您的代码
html\u字符串中
is
str(htmlresponse.text)
):

html\u字符串=“”
福
'''
按换行符
html\u字符串拆分它。拆分('\n')
将输出:

[“”,
'',
'    ',
'',
'        ',
'',
"福",,
'',
'        ',
'']
此代码将提取列表中的每个字符串,如果字符串长度为
>0

list1=[如果len(line)>0,则对html字符串中的行进行行分割('\n')]
或更紧凑:

list1=[html字符串中的行对应行。拆分('\n')如果行]
这将给你:

[“”,
'    ',
'        ',
"福",,
'        ']
但是
list1
是一个列表。要将其转换回字符串,您需要:

new\u html\u string='\n'.join(列表1)
打印
new\u html\u string
将为您提供:

总而言之:

html\u字符串=“”
福
'''
list1=[html_string.split('\n')中的行对行如果行]
新的html字符串='\n'.join(列表1)

请为初学者发布您的脚本。您有python字符串格式的html吗?是的,抱歉,已更新。
oldBlog.write(str(htmlresponse.text).replace('\n', ''))