Python 类型错误:预期的字符串或类似字节的对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35937771/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 17:10:41  来源:igfitidea点击:

TypeError: expected string or bytes-like object

pythonbeautifulsouphtml-parsing

提问by Vasanth Prabakar

I've written a scriptto parse html and print the text content only. I wanted to ignore the tags. But my program has a problem. I am not sure what it is. Please help me.

我编写了一个脚本来解析 html 并仅打印文本内容。我想忽略标签。但是我的程序有问题。我不确定它是什么。请帮我。

enter image description here

在此处输入图片说明

import urllib.request
import re
from bs4 import BeautifulSoup
url = "www.example.com"

def hi():
    dep = urllib.request.urlopen(url)
    soup = BeautifulSoup(dep, 'html.parser')
    for link in soup.find_all('p', string=True):
        result = re.sub(b'<.*?>', "", link)
        print (result)
hi() 

The website link.

网站链接

回答by Nikolay Fominyh

I believe, that you have NavigableStringin linkvariable.

我相信,你NavigableStringlink变量。

Force cast it to string like:

强制将其强制转换为字符串,例如:

for link in soup.find_all('p', string=True):
    result = re.sub(b'<.*?>', "", str(link))
    print (result)