如何使用bs4剥离字符串“ Results for 27th July 2019”中的“ Results for”?

时间:2019-07-31 14:41:13

标签: python python-3.x web-scraping beautifulsoup strip

我需要剥离“ Results for”文本,以便以后将其格式化为特定的dateformat。

问题是

当我运行不带.strip的代码时,我得到:

'Results for 27th July 2019'

当我尝试剥离文本时,出现此错误:

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

python3:

date = res.parent.find("span", {"class": "standard-headline"}).text.encode('utf8').strip("Results for ")
TypeError: a bytes-like object is required, not 'str'

有解决方法吗?我一直在研究正则表达式,但是当没有分隔符时,似乎并不能解决我的问题。

最诚挚的问候

3 个答案:

答案 0 :(得分:1)

错误是因为encode('utf8')返回bytes。您需要decode('utf-8')。它会返回一个str(),可以剥离。

答案 1 :(得分:1)

在encode('utf-8')之后,您将获得二进制字符串,因此它也希望将二进制字符串(更精确的字符列表)作为参数。 您可以使用

text.encode('utf-8').decode().strip("Results for ")

text.encode('utf-8').strip(b"Results for ")

请记住,剥离不是从字符串开头删除特定文本的最佳选择,因为这还会从尾部剥离所有R,e,s,空格等。

答案 2 :(得分:0)

我认为您需要replace方法。只需将php bin/console app:my-command --site=red_site 替换为空字符串即可。