首先我是参考了这篇文章的实例进行学习,然后发现运行失败!
一个简单的爬虫实例
报错信息:
AttributeError: module ‘urllib’ has no attribute ‘urlopen’
因为我是用python3写的,用urllib时需要加上request才不会报上面那个错。
将
import urllib
改为
import urllib.request
把有用到urllib的地方均加上.request就好了!
这些改完后运行,发现居然还报错!
报错信息:
cannot use a string pattern on a bytes-like object
这种情况解决方法就是加上html=html.decode(‘utf-8’)#python3这句代码
修改后可运行的代码如下:
import urllib.request
import re
# 根据url获取网页html内容
def getHtmlContent(url):
page = urllib.request.urlopen(url)
return page.read()
#从html中解析出所有jpg图片的url
# 百度贴吧html中jpg图片的url格式为:
def getJPGs(html):
# 解析jpg图片url的正则
jpgReg = re.compile(r'
参考资料:学习爬虫时遇到的问题TypeError: cannot use a string pattern on a bytes-like object 与解决办法