gpt4 book ai didi

python2.7.8 : TypeError: expected string or buffer with bs4 and re

转载 作者:行者123 更新时间:2023-12-01 03:58:47 26 4
gpt4 key购买 nike

我无法弄清楚为什么会出现此错误。我正在关注this tutorial提取实际文本。但我不明白这个错误。

有人可以看一下我的代码吗?

import urllib
from bs4 import BeautifulSoup
import re


url = "https://en.wikipedia.org/wiki/Python_(programming_language)" # link of website
html = urllib.urlopen(url).read() # reading and opening link
soup = BeautifulSoup(html) #parsing


for script in soup(["script", "style","a","<div id=\"bottom\" >"]): # all tags
script.extract() # clear out


for p in soup.find_all('p'): # loop for printing text
r = re.sub("<.*?>", "", p) # expression to get rid from <p> <b> etc
print r

错误:

Traceback (most recent call last):
File "C:/Users/DELL/Desktop/python/s/fyp/textextractioon.py", line 16, in <module>
r = re.sub("<.*?>", "", p)
File "C:\Python27\lib\re.py", line 151, in sub
return _compile(pattern, flags).sub(repl, string, count)
TypeError: expected string or buffer

最佳答案

将最终循环更改为:

for p in soup.find_all('p'): # loop for printing text
r = re.sub("<.*?>", "", p.text) # expression to get rid from <p> <b> etc
print r

每个 p 都来自类型类“bs4.element.Tag”:它有一些内置的方法,看一下你就会清楚了

关于python2.7.8 : TypeError: expected string or buffer with bs4 and re,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36966055/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com