如何在Python 3.x中逐行打印网页?

2024-06-28 06:17:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我只想打印一个简单网站的HTML文本。当我尝试打印时,我得到的是原始格式的文本,其中包含换行符(\n),而不是实际的新行。在

这是我的代码:

import urllib.request

page = urllib.request.urlopen('http://www.york.ac.uk/teaching/cws/wws/webpage1.html', data = None)
pageText = page.read()
pageLines = page.readlines()
print(pageLines)
print(pageText)

我试过各种各样的东西,发现了一些东西。当我试图索引pageText变量时,即使在将其转换为字符串之后,它也找不到任何\n字符。如果我尝试自己复制原始文本,使用表示为\nprint()的新行,它将\n字符转换成实际的新行,这正是我想要的。问题是,如果不自己复制,我就不能得到这个结果。在

为了说明我的意思,下面是一些HTML片段:

原始文本:

^{pr2}$

我想要的:

b'<HMTL>
<HEAD>
<TITLE>webpage1</TITLE>
</HEAD>
<BODY BGCOLOR='FFFFFf' LINK='006666' ALINK='8B4513' VLINK='006666'>

我还使用了:

page = str(page)
lines = page.split('\n')

令人惊讶的是它什么也没做。 它只是把它打印成一行。在

请帮帮我。我很惊讶我没有发现对我有用的东西。即使在论坛上,也没什么效果。在


Tags: 代码文本title网站requesthtml格式page
3条回答

一种方法是使用pythons请求模块。您可以通过执行pip安装请求来获得它(如果不使用virtualenv,则可能必须使用sudo)。在

import requests

res = requests.get('http://www.york.ac.uk/teaching/cws/wws/webpage1.html')
if res.status_code == 200: # check that the request went through
  # print the entire html, should maintain internal newlines so that when it print to screen it isn't on a single line
  print(res.content)

  #if you want to split the html into lines, use the split command like below
  #lines = res.content.split('\n')
  #print(lines)

您的字节字符串中似乎有硬编码\n。在

例如,不能在初始值上拆分。在

In [1]: s = b'<HMTL>\n<HEAD>\n'

In [2]: s.split('\n')
                                     -
TypeError                                 Traceback (most recent call last)
<ipython-input-2-e85dffa8b351> in <module>()
  > 1 s.split('\n')

TypeError: a bytes-like object is required, not 'str'

所以,你str()它,但似乎也不起作用。在

^{pr2}$

新的台词可以,但如果你用的话。在

In [4]: str(s).split('\\n')
Out[4]: ["b'<HMTL>", '<HEAD>', "'"]

你可以使用一个原始字符串来分割

In [5]: for line in str(s).split(r'\n'):
   ...:     print(line)
   ...:
b'<HMTL>
<HEAD>
'

或者,如果您不想要前导的b,您可以decode将字节串decode分割成一个字符串对象。在

In [9]: for line in s.decode("UTF-8").split('\n'):
   ...:     print(line)
   ...:
<HMTL>
<HEAD>

你得到的不是文本而是字节。如果你想要文本,就把它解码。在

b = b'<HMTL>\n<HEAD>\n<TITLE>webpage1</TITLE>\n</HEAD>\n<BODY BGCOLOR="FFFFFf" LINK="006666" ALINK="8B4513" VLINK="006666">\n'
s = b.decode()  # might need to specify an encoding
print(s)

输出:

^{pr2}$

相关问题 更多 >