Python爬取网页的所有内外链

article/2025/5/18 9:35:32

用Python爬虫,爬取网页的所有内外链

    • 项目介绍
      • 代码大纲
    • 网站详情
    • 代码详情
      • 队列
      • 内链外链
      • 请求头
    • 完整代码
    • 爬取结果

项目介绍

采用广度优先搜索方法获取一个网站上的所有外链。
首先,我们进入一个网页,获取网页的所有内链和外链,再分别进入内链中,获取该内链的所有内链和外链,直到访问完所有内链未知。

代码大纲

1、用class类定义一个队列,先进先出,队尾入队,队头出队;
2、定义四个函数,分别是爬取网页外链,爬取网页内链,进入内链的函数,以及调函数;
3、爬取百度图片(https://image.baidu.com/),先定义两个队列和两个数组,分别来存储内链和外链;程序开始时,先分别爬取当前网页的内链和外链,再分别入队,对内链外链进行判断,如果在数组中没有存在,这添加到数组中;
4、接着调用deepLinks()函数,采用循环结构,如果当前内链数量不为空时,则对存储内链的队列进行出队,并进入该内链中,再重复调用爬取网页内链和网页外链的函数,进行判断网页链接是否重复, 不重复的话,再分别将内链,外链加入到对应的队列中,不断迭代循环;
5、进入网页内所有的内链,从中搜索出所有的外链并且存储在队列中,再输出。

网站详情

在这里插入图片描述
在这里插入图片描述

代码详情

队列

队列是一种特殊的线性表,单向队列只能在一端插入数据(后),另一端删除数据(前);
它和栈一样,队列是一种操作受限制的线性表;
进行插入操作的称为队尾,进行删除操作的称为队头;
队列中的数据被称为元素;没有元素的队列称为空队列。

由于只能一端删除或者插入,所以只有最先进入队列的才能被删除,因此又被称为先进先出(FIFO—first in first out)线性表。
这里我们用class类定义一个队列,先进先出,队尾入队,队头出队,该队列要有定义以下功能:出队、入队、判断是否为空、输出队列长度、返回队头元素。

class Queue(object):#初始化队列def __init__(self):self.items = []#入队def enqueue(self, item):self.items.append(item)#出队def dequeue(self):if self.is_Empty():print("当前队列为空!!")else:return self.items.pop(0)#判断是否为空def is_Empty(self):return self.items == []#队列长度def size(self):return len(self.items)#返回队头元素,如果队列为空的话,返回Nonedef front(self):if self.is_Empty():print("当前队列为空!!")else:return self.items[len(self.items) - 1]

内链外链

内链外链的区别:
内链:是指同一网站域名下内容页面之间的互相链接。
外链:是指在别的网站导入自己网站的链接,如友情链接、外链的搭建等。
通俗的讲,内链即为带有相同域名的链接,而外链的域名则不相同。

说到内链外链,那必然离不开urllib库了,首先导入库

from urllib.parse import urlparse

用urlparse模块来解析url链接,urlparse()模块将url拆分为6部分:

scheme (协议)netloc (域名)path (路径)params (可选参数)query (连接键值对)fragment (特殊锚)
url='https://image.baidu.com/'
a, b = urlparse(url).scheme, urlparse(url).netloc
print(a)
print(b)#-----------------输出结果---------------------#
https
image.baidu.com

请求头

Header来源 用浏览器打开需要访问的网页,按F12,点开network,再按提示按ctr+R,点击name选择网站名,再看到有一个右边框第一个headers,找到request headers,这个就是浏览器的请求头, 复制其中的user-agent,复制内容。
在这里插入图片描述
这里的请求头为:

headers_={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36 Edg/89.0.774.68'}
html = requests.get(url,headers=headers_)

完整代码

class Queue(object):#初始化队列def __init__(self):self.items = []#入队def enqueue(self, item):self.items.append(item)#出队def dequeue(self):if self.is_Empty():print("当前队列为空!!")else:return self.items.pop(0)#判断是否为空def is_Empty(self):return self.items == []#队列长度def size(self):return len(self.items)#返回队头元素,如果队列为空的话,返回Nonedef front(self):if self.is_Empty():print("当前队列为空!!")else:return self.items[len(self.items) - 1]#导入库
from urllib.request import urlopen
from urllib.parse import urlparse
from bs4 import BeautifulSoup
import requests
import re
import urllib.parse
import time
import randomqueueInt = Queue()   #存储内链的队列
queueExt = Queue()   #存储外链的队列externalLinks = []
internalLinks = []#获取页面中所有外链的列表
def getExterLinks(bs, exterurl):#找出所有以www或http开头且不包含当前URL的链接for link in bs.find_all('a', href = re.compile('^(http|www)((?!'+urlparse(exterurl).netloc+').)*$')):#按照标准,URL只允许一部分ASCII字符,其他字符(如汉字)是不符合标准的,#我们的链接网址可能存在汉字的情况,此时就要进行编码。link.attrs['href'] = urllib.parse.quote(link.attrs['href'],safe='?=&:/')if link.attrs['href'] is not None:if link.attrs['href'] not in externalLinks:queueExt.enqueue(link.attrs['href'])externalLinks.append(link.attrs['href'])print(link.attrs['href'])
#     return externalLinks#获取页面中所以内链的列表    
def getInterLinks(bs, interurl):interurl = '{}://{}'.format(urlparse(interurl).scheme,urlparse(interurl).netloc)#找出所有以“/”开头的内部链接for link in bs.find_all('a', href = re.compile('^(/|.*'+urlparse(interurl).netloc+')')):link.attrs['href'] = urllib.parse.quote(link.attrs['href'],safe='?=&:/')if link.attrs['href'] is not None:if link.attrs['href'] not in internalLinks:#startsWith()方法用来判断当前字符串是否是以另外一个给定的子字符串“开头”的if(link.attrs['href'].startswith('//')):if interurl+link.attrs['href'] not in internalLinks:queueInt.enqueue(interurl+link.attrs['href'])internalLinks.append(interurl+link.attrs['href'])elif(link.attrs['href'].startswith('/')):if interurl+link.attrs['href'] not in internalLinks:queueInt.enqueue(interurl+link.attrs['href'])internalLinks.append(interurl+link.attrs['href'])else:queueInt.enqueue(link.attrs['href'])internalLinks.append(link.attrs['href'])
#     return internalLinksdef deepLinks():num = queueInt.size()while num > 1:i = queueInt.dequeue()if i is None:breakelse:print('访问的内链')print(i)print('找到的新外链')#         html = urlopen(i)html=requests.get(i,headers=headers_)time.sleep(random.random()*3)domain1 = '{}://{}'.format(urlparse(i).scheme, urlparse(i).netloc)bs = BeautifulSoup(html.content, 'html.parser')getExterLinks(bs, domain1)getInterLinks(bs, domain1)def getAllLinks(url):global num
#     html = urlopen(url)headers_={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36 Edg/89.0.774.68'}html = requests.get(url,headers=headers_)time.sleep(random.random()*3) #模拟人类行为,间隔随机的时间domain = '{}://{}'.format(urlparse(url).scheme, urlparse(url).netloc)bs = BeautifulSoup(html.content, 'html.parser')getInterLinks(bs, domain)getExterLinks(bs, domain)deepLinks()getAllLinks('https://image.baidu.com/')

爬取结果

这里我只是截取一部分:
在这里插入图片描述
在这里插入图片描述
数组中的所有内链

internalLinks-------------输出内容------------------['http://image.baidu.com','https://image.baidu.com/img/image/imageplus/index.html?fr=image','http://image.baidu.com/search/index?tn=baiduimage&ipn=r&ct=201326592&cl=2&lm=-1&st=-1&fm=result&fr=&sf=1&fmq=1567133149621_R&pv=&ic=0&nc=1&z=0&hd=0&latest=0&copyright=0&se=1&showtab=0&fb=0&width=&height=&face=0&istype=2&ie=utf-8&sid=&word=%25E5%25A3%2581%25E7%25BA%25B8','http://image.baidu.com/search/index?tn=baiduimage&ipn=r&ct=201326592&cl=2&lm=-1&st=-1&fm=result&fr=&sf=1&fmq=1461834053046_R&pv=&ic=0&nc=1&z=&se=1&showtab=0&fb=0&width=&height=&face=0&istype=2&itg=0&ie=utf-8&word=%25E5%25A4%25B4%25E5%2583%258F%23z=0&pn=&ic=0&st=-1&face=0&s=0&lm=-1','https://image.baidu.com/search/albumslist?tn=albumslist&word=%25E8%25AE%25BE%25E8%25AE%25A1%25E7%25B4%25A0%25E6%259D%2590&album_tab=%25E8%25AE%25BE%25E8%25AE%25A1%25E7%25B4%25A0%25E6%259D%2590&rn=15&fr=searchindex','https://image.baidu.com/search/albumsdetail?tn=albumsdetail&word=%25E5%259F%258E%25E5%25B8%2582%25E5%25BB%25BA%25E7%25AD%2591%25E6%2591%2584%25E5%25BD%25B1%25E4%25B8%2593%25E9%25A2%2598&fr=searchindex_album%2520&album_tab=%25E5%25BB%25BA%25E7%25AD%2591&album_id=7&rn=30','https://image.baidu.com/search/albumsdetail?tn=albumsdetail&word=%25E6%25B8%2590%25E5%258F%2598%25E9%25A3%258E%25E6%25A0%25BC%25E6%258F%2592%25E7%2594%25BB&fr=albumslist&album_tab=%25E8%25AE%25BE%25E8%25AE%25A1%25E7%25B4%25A0%25E6%259D%2590&album_id=409&rn=30','https://image.baidu.com/search/albumsdetail?tn=albumsdetail&word=%25E7%259A%25AE%25E5%25BD%25B1&fr=albumslist&album_tab=%25E8%25AE%25BE%25E8%25AE%25A1%25E7%25B4%25A0%25E6%259D%2590&album_id=394&rn=30','https://image.baidu.com/search/albumsdetail?tn=albumsdetail&word=%25E5%25AE%25A0%25E7%2589%25A9%25E5%259B%25BE%25E7%2589%2587&fr=albumslist&album_tab=%25E5%258A%25A8%25E7%2589%25A9&album_id=688&rn=30','https://image.baidu.com/search/albumsdetail?tn=albumsdetail&word=%25E8%2588%25AA%25E6%258B%258D%25E5%259C%25B0%25E7%2590%2583%25E7%25B3%25BB%25E5%2588%2597&fr=albumslist&album_tab=%25E8%25AE%25BE%25E8%25AE%25A1%25E7%25B4%25A0%25E6%259D%2590&album_id=312&rn=30','https://image.baidu.com/search/albumslist?tn=albumslist&word=%25E4%25BA%25BA%25E7%2589%25A9&album_tab=%25E4%25BA%25BA%25E7%2589%25A9&rn=15&fr=searchindex_album','http://image.baidu.com/static/html/advanced.html','https://image.baidu.com/','http://image.baidu.com/']

数组中的所有外链

externalLinks-------------输出内容------------------['http://news.baidu.com/','https://www.hao123.com/','http://map.baidu.com/','https://haokan.baidu.com/?sfrom=baidu-top/','http://tieba.baidu.com/','https://xueshu.baidu.com/','http://www.baidu.com/more/','https://pan.baidu.com','https://zhidao.baidu.com','https://baike.baidu.com','https://baobao.baidu.com','https://wenku.baidu.com','https://jingyan.baidu.com','http://music.taihe.com','https://www.baidu.com','https://www.baidu.com/','http://www.baidu.com/duty/','http://www.baidu.com/search/image_help.html','http://www.beian.gov.cn/portal/registerSystemInfo?recordcode=11000002000001','http://help.baidu.com/question','http://www.baidu.com/search/jubao.html','http://www.baidu.com/search/faq_image.html%2305']

http://chatgpt.dhexx.cn/article/8OD40Hhc.shtml

相关文章

python学习笔记(三)---python爬取网页指定内容

python学习笔记&#xff08;三&#xff09;—python爬取网页指定内容 1、利用正则匹配爬取指定内容&#xff0c;例如标题 正则表达式&#xff1a; <title>(.*?)</title> req urllib.request.Request(urlurl,headersheaders) content urllib.request.urlopen(re…

python 批量爬取网页pdf_python爬取网页内容转换为PDF文件

如何利用Python抓取PDF中的某些内容 你的问题事实上包含几部分&#xff1a; 将 PDF 转化为纯文本格式 抽取其中部分内容 格式化写入到 excel 中 转换 PDF 有很多库可以完成&#xff0c;如下是通过 pdfminer 的示例&#xff1a; from cStringIO import StringIO from pdfminer.p…

python爬取网站实例,Python爬取网页简单示例

准备材料 一&#xff1a;使用到的Python第三方库是requests 和 BeautifulSoup 二&#xff1a;选择要爬取的网页 我选择了豆瓣小组里的一个帖子回复(是微博或者微信的签名&#xff0c;个人感觉比较有意思) 地址是&#xff1a;https://www.douban.com/group/topic/80125952/ 三&a…

使用Python爬取网页中的表格保存到word

经常遇到的是爬取网页写入表格中&#xff0c;保存为csv格式、txt格式。最近接到一个任务&#xff0c;复制网页中文字和表格保存到word中&#xff0c;不仅有文字&#xff0c;还有表格。一看有100多页&#xff0c;要是一页一页的复制&#xff0c;要干到什么年月啊。 经过一番搜索…

python爬取网页表格数据并写入到excel

python爬取网页表格数据并写入到excel 获取银行网页中外汇数据&#xff1a; http://fx.cmbchina.com/Hq/History.aspx?nbr%e7%be%8e%e5%85%83&startdate2009-01-01&enddate2021-10-22&page1 代码如下&#xff1a; import datetime import reimport openpyxl …

Python 爬取网页标签内数据

1、先看运行效果&#xff0c;左边为运行后的结果&#xff0c;右边为爬取的网页内容 2、先展示代码 import requests from lxml import etree#爬取的网址 url https://sh.fang.anjuke.com/?fromnavigation #请求头 header{"user-agent": "Mozilla/5.0 (Window…

Python爬取网页文本内容

# -*- coding: utf-8 -*- from bs4 import BeautifulSoupdef second_pro(text):last_sen []while 1:last_sen.append(text.split(",")[-1])other_list text.split(",")[:-1]# 特定位置超长&#xff0c;需要处理if len(other_list) 1:last_sen.append(ot…

python爬取网页时,编码出错问题

在使用python进行爬取问题时&#xff0c;容易出现编码错误的情况&#xff0c;如&#xff1a; UnicodeEncodeError: ‘gbk’ codec can’t encode character ‘\xb9’ in position 61513: illegal multibyte sequence 程序代码: headers {"User-Agent":"Mozi…

python爬取网页图片详解

文章目录 什么是爬虫爬取网页图片实现步骤第一步&#xff1a;打开所操作的网站&#xff08;任意一个网站&#xff09;第二步&#xff1a;通过python访问这个网站第三步&#xff1a;点击F12查询相关信息第四步&#xff1a;爬取图片&#xff0c;下载到本地第五步&#xff1a;显示…

python爬取网页信息

PythonSpider项目 Python爬虫是用Python编程语言实现的网络爬虫&#xff0c;主要用于网络数据的抓取和处理&#xff0c;相比于其他语言&#xff0c;Python是一门非常适合开发网络爬虫的编程语言&#xff0c;大量内置包&#xff0c;可以轻松实现网络爬虫功能。Python爬虫可以做…

python爬取网页图片

python爬取网页图片 爬取数据一般分为三步&#xff1a; 爬取网页信息解析爬取来的数据保存数据 找到自己想要爬取的网页&#xff0c;找到user-agent 代码实现 首先导入需要用到的包 from bs4 import BeautifulSoup #网页解析&#xff0c;获取数据 import re #正…

走好这六步,python爬虫爬取网页数据手到擒来~

前言&#xff1a; 用python的爬虫爬取数据真的很简单&#xff0c;只要掌握这六步就好&#xff0c;也不复杂。以前还以为爬虫很难&#xff0c;结果一上手&#xff0c;从初学到把东西爬下来&#xff0c;一个小时都不到就解决了。 python爬虫六步走 第一步&#xff1a;安装requ…

css样式优先级详解

很多人在写代码的过程中会出现css样式冲突的情况&#xff0c;那么我们怎样才能应用我们想用的样式&#xff0c;下面就个人经验写了一点总结&#xff01; 1.权值&#xff08;浏览器是根据权值来判断使用哪种css样式的&#xff0c;哪种样式权值高就使用哪种样式&#xff09; ①标…

css样式优先级问题

此片博客为参考博客&#xff0c;更多详情可看:https://www.cnblogs.com/ombre/p/7418667.html 官方表述的CSS样式优先级如下: 通用选择器(*&#xff09;<元素(类型)选择器<类名选择器<属性选择器<伪类选择器<ID选择器<内联样式 其中内联样式只能通过style&…

前端基础-CSS样式的优先级

样式的优先级&#xff08;了解&#xff09; 1.强制优先级&#xff08;important&#xff09; 语法&#xff1a;样式属性:值 !important; 示意图 注意&#xff1a;只针对当前这一条css属性 2.选择器优先级 伪对象选择器>!important>行内样式>id选择器>class选…

HTML——CSS样式优先级

代码 <!DOCTYPE html> <html lang"en"> <head><meta charset"UTF-8"><meta http-equiv"X-UA-Compatible" content"IEedge"><meta name"viewport" content"widthdevice-width, initia…

关于CSS样式优先级

设定Li 当中的a链接样式的时候&#xff0c;设了几次没成功。考虑跟优先级有关。转载这篇文章&#xff0c;供自己记录学习&#xff0c;与新手们讨论交流 一般情况下&#xff1a; [1位重要标志位] > [4位特殊性标志] > 声明先后顺序 !important > [ id > class &g…

JavaWeb_CSS(5)_样式优先级

本系列博客汇总在这里&#xff1a;JavaWeb_CSS 汇总 目录 样式优先级示例 样式优先级 由上到下&#xff0c;由外到内。优先级由低到高。 示例 CSS 文件1p {text-align: center;color: red; }CSS 文件2p {text-align: center;color: green; }/*div 表示 p 标签往内一层*/ d…

CSS 样式优先级权重

CSS的样式优先级可分为四大类&#xff1a; 1、&#xff01;important 无论何种引入方式和选择器&#xff0c;优先级都是最高的&#xff1b; 2、行内样式 style"" 行内样式的优先级要高于嵌入和外链&#xff0c;嵌入和外链如果使用的选择器相同就看他们在页面中插…

html中css样式的优先级规则

CSS2.1 中规定了关于 CSS 规则 Specificity&#xff08;特异性&#xff09;的计算方式&#xff0c;用一个四位的数字串&#xff08;注&#xff1a;CSS2 中是用三位&#xff09;来表示&#xff0c;最后以 Specificity 的高低判断 CSS 的优先权。Specificity 具体的计算规则&…