简介
上一篇写的时候有点长了,接下来继承把美空网的爬虫写完,这套教程中编写的爬虫在现实的工作中能够并不能给你增添若干有价值的手艺点,由于它只是一套入门的教程,老鸟你自动绕过就能够了,或许带带我也行。
爬虫剖析
起首,我们已爬取到了N多的用户个人主页,我经由历程链接拼接猎取到了
http://www.moko.cc/post/da39d…
在这个页面中,我们要找几个中心的症结点,发明平面拍摄
点击进入的是图片列表页面。
接下来最先代码走起。
猎取一切列表页面
我经由历程上篇博客已猎取到了70000(现实测试50000+)用户数据,读取到python中。
这个处所,我使用了一个比较好用的python库pandas,人人假如不熟悉,先模仿我的代码就能够了,我把解释都写完全。
import pandas as pd
# 用户图片列表页模板
user_list_url = "http://www.moko.cc/post/{}/list.html"
# 寄存一切用户的列表页
user_profiles = []
def read_data():
# pandas从csv内里读取数据
df = pd.read_csv("./moko70000.csv") #文件在本文末端能够下载
# 去掉昵称反复的数据
df = df.drop_duplicates(["nikename"])
# 根据粉丝数量举行降序
profiles = df.sort_values("follows", ascending=False)["profile"]
for i in profiles:
# 拼接链接
user_profiles.append(user_list_url.format(i))
if __name__ == '__main__':
read_data()
print(user_profiles)
数据已拿到,接下来我们须要猎取图片列表页面,找一下规律,看到重点的信息以下所示,找对位置,就是正则表达式的事变了。
疾速的编写一个正则表达式<p class="title"><a hidefocus="ture".*?href="(.*?)" class="mwC u">.*?\((\d+?)\)</a></p>
引入re,requests模块
import requests
import re
# 猎取图片列表页面
def get_img_list_page():
# 牢固一个地点,轻易测试
test_url = "http://www.moko.cc/post/da39db43246047c79dcaef44c201492d/list.html"
response = requests.get(test_url,headers=headers,timeout=3)
page_text = response.text
pattern = re.compile('<p class="title"><a hidefocus="ture".*?href="(.*?)" class="mwC u">.*?\((\d+?)\)</a></p>')
# 猎取page_list
page_list = pattern.findall(page_text)
运转获得效果
[('/post/da39db43246047c79dcaef44c201492d/category/304475/1.html', '85'), ('/post/da39db43246047c79dcaef44c201492d/category/304476/1.html', '2'), ('/post/da39db43246047c79dcaef44c201492d/category/304473/1.html', '0')]
继承完美代码,我们发明上面猎取的数据,有”0″的发生,须要过滤掉
# 猎取图片列表页面
def get_img_list_page():
# 牢固一个地点,轻易测试
test_url = "http://www.moko.cc/post/da39db43246047c79dcaef44c201492d/list.html"
response = requests.get(test_url,headers=headers,timeout=3)
page_text = response.text
pattern = re.compile('<p class="title"><a hidefocus="ture".*?href="(.*?)" class="mwC u">.*?\((\d+?)\)</a></p>')
# 猎取page_list
page_list = pattern.findall(page_text)
# 过滤数据
for page in page_list:
if page[1] == '0':
page_list.remove(page)
print(page_list)
猎取到列表页的进口,下面就要把一切的列表页面悉数拿到了,这个处所须要点击下面的链接检察一下
http://www.moko.cc/post/da39d…
本页面有分页,4页,每页显现数据4*7=28
条
所以,基础计算公式为 math.ceil(85/28)
接下来是链接生成了,我们要把上面的链接,转换成
http://www.moko.cc/post/da39db43246047c79dcaef44c201492d/category/304475/1.html
http://www.moko.cc/post/da39db43246047c79dcaef44c201492d/category/304475/2.html
http://www.moko.cc/post/da39db43246047c79dcaef44c201492d/category/304475/3.html
http://www.moko.cc/post/da39db43246047c79dcaef44c201492d/category/304475/4.html
page_count = math.ceil(int(totle)/28)+1
for i in range(1,page_count):
# 正则表达式举行替代
pages = re.sub(r'\d+?\.html',str(i)+".html",start_page)
all_pages.append(base_url.format(pages))
当我们回去到足够多的链接以后,关于初学者,你能够先干这么一步,把这些链接存储到一个csv文件中,轻易后续开辟
# 猎取一切的页面
def get_all_list_page(start_page,totle):
page_count = math.ceil(int(totle)/28)+1
for i in range(1,page_count):
pages = re.sub(r'\d+?\.html',str(i)+".html",start_page)
all_pages.append(base_url.format(pages))
print("已猎取到{}条数据".format(len(all_pages)))
if(len(all_pages)>1000):
pd.DataFrame(all_pages).to_csv("./pages.csv",mode="a+")
all_pages.clear()
让爬虫飞一会,我这边拿到了80000+条数据
好了,列表数据有了,接下来,我们继承操纵这个数据,是否是觉得速率有点慢,代码写的有点LOW,好吧,我认可这是给新手写的实在就是懒
,我转头在用一篇文章把他给改成面向对象和多线程的
我们接下来基于爬取到的数据再次举行剖析
比方 http://www.moko.cc/post/nimus… 这个页面中,我们须要猎取到,赤色框框的地点,为何要或许这个?由于点击这个图片以后进入内里才是完全的图片列表。
我们照样运用爬虫猎取
几个步骤
- 轮回我们适才的数据列表
- 抓取网页源码
- 正则表达式婚配一切的链接
def read_list_data():
# 读取数据
img_list = pd.read_csv("./pages.csv",names=["no","url"])["url"]
# 轮回操纵数据
for img_list_page in img_list:
try:
response = requests.get(img_list_page,headers=headers,timeout=3)
except Exception as e:
print(e)
continue
# 正则表达式猎取图片列表页面
pattern = re.compile('<a hidefocus="ture" alt="(.*?)".*? href="(.*?)".*?>VIEW MORE</a>')
img_box = pattern.findall(response.text)
need_links = [] # 待抓取的图片文件夹
for img in img_box:
need_links.append(img)
# 建立目次
file_path = "./downs/{}".format(str(img[0]).replace('/', ''))
if not os.path.exists(file_path):
os.mkdir(file_path) # 建立目次
for need in need_links:
# 猎取概况页面图片链接
get_my_imgs(base_url.format(need[1]), need[0])
上面代码几个重点处所
pattern = re.compile('<a hidefocus="ture" alt="(.*?)".*? href="(.*?)".*?>VIEW MORE</a>')
img_box = pattern.findall(response.text)
need_links = [] # 待抓取的图片文件夹
for img in img_box:
need_links.append(img)
猎取到抓取目次,这个处所,我婚配了两个部份,重要用于建立文件夹
建立文件夹须要用到 os 模块,记得导入一下
# 建立目次
file_path = "./downs/{}".format(str(img[0]).replace('/', ''))
if not os.path.exists(file_path):
os.mkdir(file_path) # 建立目次
猎取到概况页面图片链接以后,在举行一次接见抓取一切图片链接
#猎取概况页面数据
def get_my_imgs(img,title):
print(img)
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36"}
response = requests.get(img, headers=headers, timeout=3)
pattern = re.compile('<img src2="(.*?)".*?>')
all_imgs = pattern.findall(response.text)
for download_img in all_imgs:
downs_imgs(download_img,title)
末了编写一个图片下载的要领,一切的代码完成,图片保留当地的地点,用的是时候戳。
def downs_imgs(img,title):
headers ={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36"}
response = requests.get(img,headers=headers,timeout=3)
content = response.content
file_name = str(int(time.time()))+".jpg"
file = "./downs/{}/{}".format(str(title).replace('/','').strip(),file_name)
with open(file,"wb+") as f:
f.write(content)
print("终了")
运转代码,等着收图
代码运转一下,发明报错了
缘由是途径的题目,在途径中涌现了…这个特别字符,我们须要相似上面处置惩罚/
的体式格局处置惩罚一下。自行处置惩罚一下吧。
数据猎取到,就是这个模样的
代码中须要完美的处所
- 代码分成了两部份,而且是面向历程的,异常不好,须要革新
- 收集要求部份反复代码过量,须要举行笼统,而且加上错误处置惩罚,现在是有能够报错的
- 代码单线程,效力不高,能够参照前两篇文章举行革新
- 没有模仿登录,最多只能爬取6个图片,这也是为何先把数据保留下来的缘由,轻易后期直接革新