马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
import urllib.request
import re
import os
def open_url(url):
req =urllib.request.Request(url)
req.add_header('User-Agent',' Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.74 Safari/537.36 Edg/99.0.1150.46')
page = urllib.request.urlopen(req)
html = page.read().decode('utf-8')
return html
def get_img(html):
p = r'<img class="BDE_Image".*?src="([^"]*\.jpg)".*?>'
imglist = re.findall(p,html)
try:
os.mkdir('NewPics')
except FileExistsError:
pass
os.chdir("NewPics")
for each in imglist:
filename = each.split("/")[-1]
urllib.request.urlretrieve(each,filename,None)
if __name__ == '__main__':
url = 'https://tieba.baidu.com/p/7766911770'
get_img(open_url(url))
正则表达式不对:
import urllib.request
import re
import os
def open_url(url):
req =urllib.request.Request(url)
req.add_header('User-Agent',' Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.74 Safari/537.36 Edg/99.0.1150.46')
page = urllib.request.urlopen(req)
html = page.read().decode('utf-8')
return html
def get_img(html):
p = r'<img class="BDE_Image".*?src="([^"]*\.jpg)[^"]*".*?>' # 修改了正则表达式
imglist = re.findall(p,html)
try:
os.mkdir('NewPics')
except FileExistsError:
pass
os.chdir("NewPics")
for each in imglist:
filename = each.split("/")[-1]
urllib.request.urlretrieve(each,filename,None)
if __name__ == '__main__':
url = 'https://tieba.baidu.com/p/7766911770'
get_img(open_url(url))
|