感觉网上的文章都是以这篇为中心去照搬的
https://www.cnblogs.com/zhaof/p/7092400.html
不过这篇文章也确实把广度跟深度优先算法说完了,但感觉没有爬取实例的话还是挺抽象的,所以就配合例子说一下广/深度优先。
首先我们要知道:
广度优先: 把同一等级的url全部爬取网然后再往下一级的url去爬取
深度优先: 把一个分页的所有等级的url从浅到深爬取完后再爬取另一个分页
我们以 https://www.dytt8.net/index.htm这个电影网为例子
我们的目标是 进入每一个分类的 更多页面

然后以每一个更多页面的下一页为深度等级去爬取

广度优先:
import requests,re
from parsel import Selector
from urllib.parse import urljoin
def url_level_queue(url):
base_url = "https://www.dytt8.net"
if url is None:
return
url_list = []
next_page_url = []
resp_shouye = requests.get(url=url,headers=headers)
if resp_shouye.text:
print(resp_shouye.url)
else:
return
selector_shouye = Selector(resp_shouye.text)
#获取所有"更多"的起始页分页
url_list = selector_shouye.xpath("//div[@class='title_all']//em/a/@href").getall()
#迅雷不是我们要的所以删除
del url_list[1]
while url_list:
gengduo_url = url_list.pop(0)
if gengduo_url[0:4] !='http':
new_url = base_url + gengduo_url
print(new_url)
#所有的分页url
resp_new_url = requests.get(url=new_url,headers=headers)
#获取的网页是乱码,但不妨碍我们用正则去获取下一页的url
next_page = re.findall(r"<a href='(.+)'>ÏÂÒ»Ò³",str(resp_new_url.text))[0]
#获得所有分页url的nextpage 第二页
next_page_url.append(urljoin(resp_new_url.url,next_page))
while next_page_url:
node_next = next_page_url.pop(0)
print(node_next) #2
resp_next_url = requests.get(url=node_next,headers=headers)#2
next_page = re.findall(r"<a href='(.+)'>ÏÂÒ»Ò³",str(resp_next_url.text))[0]#2找3
next_page_url.append(urljoin(resp_next_url.url,next_page))#最后一项添加新的下一页
headers = {
'User-Agent':"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Safari/537.36",
}
url = "https://www.dytt8.net/"
url_level_queue(url)
``
深度优先:采取的是递归
import requests,re
from parsel import Selector
from urllib.parse import urljoin
def url_tree(url):
resp_shou = requests.get(url=url,headers=headers)
if resp_shou:
print(resp_shou.url)
next_page = re.findall(r"<a href='(.+)'>ÏÂÒ»Ò³",str(resp_shou.text))
if next_page:
#为了不把一个深度全部爬取完,所以只爬取前5页
if re.findall(r'.+_(\d+)\.html',str(next_page))[0] == '6':
return
next_page_url = urljoin(resp_shou.url,next_page[0])
return url_tree(next_page_url)
base_url = "https://www.dytt8.net"
headers = {
'User-Agent':"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Safari/537.36",
}
url = "https://www.dytt8.net/"
resp_shouye = requests.get(url=url,headers=headers)
if resp_shouye.text:
print(resp_shouye.url)
selector_shouye = Selector(resp_shouye.text)
#获取所有"更多"的起始页分页
more_page = selector_shouye.xpath("//div[@class='title_all']//em/a/@href").getall()
#其中有一页是迅雷下载区不是我们想要的案例,所以要删除
del more_page[1]
for each_more_page in more_page:
if each_more_page[0:4] != 'http':
new_gengduo_url = base_url + str(each_more_page)
url_tree(new_gengduo_url)
代码写得很烂,但不妨碍我们去理解
本文通过实例详细解析了爬虫中广度优先与深度优先算法的应用,对比了两种算法在网页爬取过程中的不同策略,帮助读者深入理解算法原理。
1397





