proxy = None
#构造请求头
headers = {“User-agent”:self.user_agent}
#下载页面
result = self.download(url,headers,proxy = proxy,num_retries = self.num_retries)
‘’’
file = open(“f:\\bilibili.html”,“wb”)
file.write(result[“html”])
file.close()
‘’’
if self.cache:
#如果有缓存方式,缓存网页
self.cache[url] = result
print(url,“页面下载完成”)
return result[“html”]
def download(self,url,headers,proxy,num_retries,data=None):
‘’’
用于下载一个页面,返回页面和与之对应的状态码
‘’’
#构建请求
request = urllib.request.Request(url,data,headers or {})
request.add_header(“Cookie”,“finger=7360d3c2; UM_distinctid=15c59703db998-0f42b4b61afaa1-5393662-100200-15c59703dbcc1d; pgv_pvi=653650944; fts=1496149148; sid=bgsv74pg; buvid3=56812A21-4322-4C70-BF18-E6D646EA78694004infoc; CNZZDATA2724999=cnzz_eid%3D214248390-1496147515-https%253A%252F%252Fwww.baidu.com%252F%26ntime%3D1496805293”)
request.add_header(“Upgrade-Insecure-Requests”,“1”)
opener = self.opener or urllib.request.build_opener()
if proxy:
#如果有代理IP,使用代理IP
opener = urllib.request.build_opener(urllib.request.ProxyHandler(proxy))
try:
#下载网页
response = opener.open(request)
print(“code是”,response.code)
html = response.read().decode()
code = response.code
except Exception as e:
print(“下载出现错误”,str(e))
html = ‘’
if hasattr(e,“code”):
code =e.code
if num_retries > 0 and 500<code<600:
#如果错误不是未找到网页,则重新下载num_retries次
return self.download(url,headers,proxy,num_retries-1,data)
else:
code = None
print(html)
return {“html”:html,“code”:code}
class Throttle:
‘’’
按照延时,请求,代理IP等下载网页,处理网页中的link的类
‘’’
def __init__(self, delay):
self.delay = delay
self.domains = {}
def wait(self, url):
‘’’
每下载一个html之间暂停的时间
‘’’
获得域名
domain = urllib.parse.urlparse(url).netloc
获得上次访问此域名的时间
las_accessed = self.domains.get(domain)
if self.delay > 0 and las_accessed is not None:
计算需要强制暂停的时间 = 要求的间隔时间 - (现在的时间 - 上次访问的时间)
sleep_secs = self.delay - (datetime.datetime.now() - las_accessed).seconds
if sleep_secs > 0:
time.sleep(sleep_secs)
存储此次访问域名的时间
self.domains[domain] = datetime.datetime.now()
然后是实现爬虫功能的类
import time
import threading
import re
import urllib.parse
import datetime
from bs4 import BeautifulSoup
from Downloader import Downloader
from MongoCache import MongoCache
SLEEP_TIME = 1
def get_links(html):
‘’’
获得一个页面上的所有链接
‘’’
bs = BeautifulSoup(html, “lxml”)
link_labels = bs.find_all(“a”)
for link in link_labels:
return [link_label.get(‘href’, “default”) for link_label in link_labels]
def same_domain(url1, url2):
‘’’
判断域名书否相同
‘’’
return urllib.parse.urlparse(url1).netloc == urllib.parse.urlparse(url2).netloc
def normalize(seed_url, link):
‘’’
用于将绝对路径转换为相对路径
‘’’
link, no_need = urllib.parse.urldefrag(link)
return urllib.parse.urljoin(seed_url, link)
def threader_crawler(seed_url,resource_regiex=None,link_regiex = “.*”,delay=5,cache=None,download_source_callback=None,user_agent=“wswp”,proxies=None, num_retries=1, max_threads=10, timeout=60,max_url=500):
downloaded = []
crawl_queue = [seed_url]
seen = set([seed_url])
D = Downloader(cache = cache,delay = delay,user_agent=user_agent,proxies=proxies,num_retries=num_retries,timeout=timeout)
print(user_agent)
def process_queue():
while True:
links = []
try:
url = crawl_queue.pop()
except IndexError:
break
else:
html = D(url)
downloaded.append(url)
if download_source_callback:
if resource_regiex and re.match(resource_regiex,url):
download_source_callback(url,html)
links.extend([link for link in get_links(html) if re.match(link_regiex,link)])
for link in links:
link = normalize(seed_url, link)
if link not in seen:
seen.add(link)
if same_domain(seed_url,link):
crawl_queue.append(link)
print(“已经发现的总网页数目为”,len(seen))
print(“已经下载过的网页数目为”,len(downloaded))
print(“还没有遍历过的网页数目为”,len(crawl_queue))
threads=[]
while threads or crawl_queue:
if len(downloaded) == max_url:
return
for thread in threads:
if not thread.is_alive():
threads.remove(thread)
while len(threads) < max_threads and crawl_queue:
print(“线程数量为”, len(threads))
thread = threading.Thread(target=process_queue)
thread.setDaemon(True)
thread.start()
print(“线程数量为”, len(threads))
threads.append(thread)
def main():
starttime = datetime.datetime.now()
threader_crawler(“http://www.xicidaili.com/”,max_threads=1,max_url=10,user_agent=“Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36”)
endtime = datetime.datetime.now()
print(“花费时间”,(endtime-starttime).total_seconds())
if __name__ == “__main__”:
main()
经过测试,多线程爬虫速度要远远高于单个线程爬取,简单测试结果如下
开启30个线程爬取一百个网站用时31秒,平均一个用时0.31秒
开启10个线程爬取一百个网页用时69秒,平均一个用时0.69秒
开启1 个线程爬取一百个网站用时774秒,平均一个用时7.74秒
顺便实现了一个测试用的资源下载类,用于将电影天堂的所有资源页的电影保存到数据库
from lxml import etree
from pymongo import MongoClient
import urllib.request
import re
class download_source_callback:
def __init__(self,client=None):
if client:
self.client = client
else:
self.client = MongoClient(“localhost”,12345)
self.db = self.client.cache
def __call__(self,url,html):
title_regiex = “
class_regiex = “类 别(.*?)<”
director_regiex = “.*导 演(.*?)<”
content_regiex = “简 介(.*?)
◎”
imdb_regiex = “IMDb评分 (.*?)<”
douban_regiex = “豆瓣评分(.*?)<”
自我介绍一下,小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。
深知大多数Python工程师,想要提升技能,往往是自己摸索成长或者是报班学习,但对于培训机构动则几千的学费,着实压力不小。自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!
因此收集整理了一份《2024年Python开发全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。
既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上Python开发知识点,真正体系化!
由于文件比较大,这里只是将部分目录大纲截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且后续会持续更新
如果你觉得这些内容对你有帮助,可以添加V获取:vip1024c (备注Python)
一、Python所有方向的学习路线
Python所有方向的技术点做的整理,形成各个领域的知识点汇总,它的用处就在于,你可以按照下面的知识点去找对应的学习资源,保证自己学得较为全面。
二、Python必备开发工具
工具都帮大家整理好了,安装就可直接上手!
三、最新Python学习笔记
当我学到一定基础,有自己的理解能力的时候,会去阅读一些前辈整理的书籍或者手写的笔记资料,这些笔记详细记载了他们对一些技术点的理解,这些理解是比较独到,可以学到不一样的思路。
四、Python视频合集
观看全面零基础学习视频,看视频学习是最快捷也是最有效果的方式,跟着视频中老师的思路,从基础到深入,还是很容易入门的。
五、实战案例
纸上得来终觉浅,要学会跟着视频一起敲,要动手实操,才能将自己的所学运用到实际当中去,这时候可以搞点实战案例来学习。
六、面试宝典
简历模板![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/e609d9de17e680ccba27f351612a0860.png#pic_center)
的。
五、实战案例
纸上得来终觉浅,要学会跟着视频一起敲,要动手实操,才能将自己的所学运用到实际当中去,这时候可以搞点实战案例来学习。
六、面试宝典