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

标签 python beautifulsoup

我无法弄清楚为什么会出现此错误。我正在关注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/

相关文章:

python - 面向对象与基于向量的编程

python - 在 Selenium 中使用 find_element_by_class_name 遍历多个类

python - 如何让 Beautiful Soup 输出 HTML 实体?

python - 避免 Python 3 中的堆栈溢出

python - 提取 URL 的特定部分

python - 如果找到某些字符串,则提取链接和文本 - BeautifulSoup

python - 由于 bs4 vs BeautifulSoup 导致导入错误

javascript - 如何使用 BeautifulSoup 从网页上的一些 JavaScript 中提取一长串文本?

python - Pandas 获取每组条件第一次出现的列值

python - 如何使用python和beautiful soup将一个html页面拆分为多个页面