与一起使用.split()函数时出错urllib.reques

2024-06-25 23:00:33 发布

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

为了获得头条新闻,我试图把bbc的消息来源分成两部分:

import urllib.request

url = 'http://www.bbc.com/'
page = urllib.request.urlopen(url)
contents = page.read()
page.close()

split1 = '<a class="media__link" href="/news/world-us-canada-39965107" rev="hero1|headline">\n'
split2 = '\n</a>'

title = contents.split(split1)[1].split(split2)[1]

print(title)

但我得到了一个错误:

^{pr2}$

Tags: importhttpurltitlerequestwwwcontentspage
1条回答
网友
1楼 · 发布于 2024-06-25 23:00:33

HTTPResponse.read([amt]):

Reads and returns the response body, or up to the next amt bytes.

contents = page.read()

返回一个bytes对象,而不是str。因此拆分分隔符也必须是bytes对象。只需在字符串前面添加一个b。在

^{pr2}$

相关问题 更多 >