TypeError: cannot use a string pattern on a bytes-like object的解決辦法


#!/usr/python3
import re
import urllib.request
def gethtml(url):
    page=urllib.request.urlopen(url)
    html=page.read()
    return html
def getimg(html):
    reg = r'src="(.*?\.jpg)"'
    img=re.compile(reg)
    html=html.decode('utf-8') # python3
    imglist=re.findall(img,html)
    x = 0
    for imgurl in imglist:
        urllib.request.urlretrieve(imgurl,'%s.jpg'%x)
        x = x+1
html=gethtml("http://news.ifeng.com/a/20161115/50243265.html")

print(getimg(html))

代碼中紅色字體部分均為Python3.0及以上版本在學到爬蟲是需要注意的,如果沒有這些紅色的代碼的話可能會出現以下情況:

1.TypeError: cannot use a string pattern on a bytes-like object  這種情況解決方法就是加上html=html.decode('utf-8')#python3這句代碼;

2.AttributeError: module 'urllib' has no attribute 'urlopen'這種情況的解決辦法就是將urllib改成urllib.request就行了。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM