如何解决TypeError: expected string or buffer?

求助代码
import urllib2
import re
import os
headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:67.0) Gecko/20100101 Firefox/67.0", }
urlcontent = urllib2.urlopen('http://news.qq.com/a/20120506/index.htm')
#print urlcontent
rege = re.compile(r"/a/\d{8}/\d{6}.htm")
get_url = re.findall(rege,urlcontent)
print get_url

exit()

会报错
C:\Users\Min\PycharmProjects\untitled\venv\Scripts\python.exe C:/Users/Min/PycharmProjects/untitled/tcpy2.py
Traceback (most recent call last):
File "C:/Users/Min/PycharmProjects/untitled/tcpy2.py", line 8, in
get_url = re.findall(rege,urlcontent)
File "C:\Users\Min\PycharmProjects\untitled\venv\lib\re.py", line 181, in findall
return _compile(pattern, flags).findall(string)
TypeError: expected string or buffer

Process finished with exit code 1

2个回答

错误种类:TypeError: expected string or buffer

具体错误解释:这是因为返回的变量不是字符类型,而导致此错误

urllib2.urlopen 返回的是一个 Socket 对象,需要通过 read 操作读取它的内容才能得到一个文本。修正代码为:

urlcontent = urllib2.urlopen('http://news.qq.com/a/20120506/index.htm').read()
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问

相似问题

2
为什么使用Node.replaceChild报Uncaught TypeError: Cannot read property 'replaceChild' of null
1
python温度转换提示“TypeError: string indices must be integers”
1
scipy解非线性方程组报错TypeError: 'int' object is not callable
2
Python使用类装饰器出现报错:TypeError: test2() missing 1 required positional argument: 'b'
1
python3 sorted()函数报错 TypeError: '<' not supported between instances of 'str' and 'int'
2
TypeError: unhashable type: 'list' 错误怎么处理
1
Python, TypeError: APP() takes no arguments
2
zepto animate动画报错 已引入fx.js报Uncaught TypeError: this.bind is not a function的错误
0
nodejs.TypeError: Cannot read property 'toLowerCase' of undefined
1
TypeError: expected str, bytes or os.PathLike object, not tuple此报错有大神遇到过吗怎么解决
3
python运行脚本时提示TypeError: float argument required, not str这个错误,有大佬知道原因吗,望解答
1
python纸牌类TypeError: object of type 'FrenchDeck' has no len()
2
python中绘制世界地图TypeError: argument of type 'Key' is not iterable。
1
爬取知乎信息报错--TypeError: string indices must be integers
1
爬取途牛机票信息报错--TypeError: string indices must be integers
1
python3使用imshow函数出现错误TypeError: Expected cv::UMat for argument 'mat'怎么改?
1
matplotlib: TypeError: unsupported operand type(s) for -: 'str' and 'float'求解决
1
TypeError: unsupported operand type(s) for ** or pow(): 'dict' and 'int'
1
TypeError: 'NoneType' object is not iterable到底时什么原因导致的,代码哪里有问题?已解决。
2
Python语法错误:TypeError: string indices must be integers