练手爬虫用urllib模块获取

2022-10-17,,,,

练手爬虫urllib模块获取

有个人看一段python2的代码有很多错误

import re
import urllib

def gethtml(url):
    page = urllib.urlopen(url)
    html = page.read()
    return html

def getimg(html):
    reg = r'src="(.+?\.jpg)" pic_ext'
    imgre = re.compile(reg)
    imglist = re.findall(imgre,html)
    return imglist 

html = gethtml("https://zwk365.com") //攒外快网
print getimg(html)

修改后python3的代码

import re
import urllib.request

def gethtml(url):
    page = urllib.request.urlopen(url) #获取网站
    html = page.read() #内容读取,返回的html是字节的格式
    return html

def getimg(html):
    # print(str(html,encoding='utf8'))   #内容以爬下来为准而不是网站上的
    reg = 'data-original="(.*?)"'  #设置下内容的re格式
    imglist = re.findall(reg,str(html,encoding='utf8'),re.s)
    return imglist

html = gethtml("https://zwk365.com")
print(getimg(html))

《练手爬虫用urllib模块获取.doc》

下载本文的Word格式文档,以方便收藏与打印。