马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
import urllib.request
import os
import re
import base64
def url_open(url):
# 添加文件头
req = urllib.request.Request(url)
req.add_header('User-Agent',
'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.105 Safari/537.36')
# 访问页面
response = urllib.request.urlopen(req)
html = response.read()
return html
# 获取页码
def get_page(url):
html = url_open(url).decode('utf-8')
a = r'<span class="current-comment-page">\[(\d+)]'
num = re.findall(a,html)
return num[0]
# 获取图片地址
def find_imgs(url):
html = url_open(url).decode('utf-8')
a = r'<img src="([^"]+\.jpg)"'
img_urls = re.findall(a,html)
return img_urls
# 保存图片
def save_imgs(folder, img_addrs):
for each in img_addrs:
filename = each.split('/')[-1]
with open(filename,'wb') as f:
each_url = 'http:' + each
img = url_open(each_url)
f.write(img)
def download_mm(folder='ooxx', pages=20):
# 创建文件夹
os.mkdir(folder)
# 保存文件夹
os.chdir(folder)
url = 'http://jandan.net/ooxx/'
# 获取页码
page_num = int(get_page(url))
for i in range(pages):
page_num -= 1
# 进行base64加密
num = '20200901-' + str(page_num)
bytes_num = num.encode('utf-8')
str_num = base64.b64encode(bytes_num).decode('utf-8')
# 获取下一页地址
page_url = url + str_num + '#comments'
# 获取页面内图片地址
img_addrs = find_imgs(page_url)
# 保存页面到指定的文件夹
save_imgs(folder, img_addrs)
# 完毕
print("煎蛋网第%d页爬取完毕!" % page_num)
print("结束退出!^_^")
# 调用主函数
if __name__ == '__main__':
download_mm()
主题:煎蛋网随手拍
方法:re正则表达式、os模块文件的函数、base64解加密
问题1:如何用xpath方法来摹写正则表达式的代码部分呢?
问题2:还可以再进行优化!
每次回帖奖励: 1鱼币, 奖励 10次, 每人最多可获得 1次, 中奖率 50% |