python3简单爬虫 (爬取各个网站上的图片)

时间:2022-02-09 02:59:51

不多说。Python能做出东西。这是对编程初学者的莫大激励了吧。2333333

下面就放码了。

第一个爬虫:

import urllib.request
import re
import os
foot='huaban001'
url_re=re.compile(r'<img src="(http://img.hb.aicdn.com/.+?)"')
url='http://huaban.com/favorite/beauty/'
def url_open(url):
html=urllib.request.urlopen(url).read()
return html
def get_img_adds(html):
img_addrs=url_re.findall(html)
img_addrs=list(set(img_addrs))
img_addrs.remove('http://img.hb.aicdn.com/23a58517fb73f86bca85937f069724486b3e00a44caa-GMc99I_sq75sf')
return img_addrs
def save_img(img_addrs,filename=0):
for each in img_addrs:
with open(str(filename)+'.jpg','wb') as f:
filename+=1
img=url_open(each)
f.write(img)
def download_huaban_img():
os.mkdir(foot)
os.chdir(foot)
html=url_open(url)
img_addrs=get_img_adds(html.decode('utf-8'))
save_img(img_addrs)
if __name__=='__main__':
download_huaban_img()
爬取花瓣网站上的图片。未涉及模拟登陆也未涉及下拉页面。只是简单的爬取官方页面上的图。

代码实在是写得很丑啊233333.

第二个爬虫:

爬取某些网站上的代理IP

import urllib.request
import re
ip_re=re.compile(r'(?:(?:[0,1]?\d?\d|2[0-4]\d|25[0-5])\.){3}(?:[0,1]?\d?\d|2[0-4]\d|25[0-5])')
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/48.0.2564.109 Safari/537.36')
html=urllib.request.urlopen(req).read().decode('UTF-8')
return html
url='http://www.xicidaili.com/'
html=url_open(url)
ip_addrs=ip_re.findall(html)
for each in ip_addrs:
print(each)
思路一样很简单。

主要就是正则表达式的书写。233333

用Python自带的库的爬虫思路都差不多,也就不继续放我丑的不行的代码了。

下面准备看requests实现模拟登陆了。希望不要太复杂啊。

python3简单爬虫 (爬取各个网站上的图片)