脚本如何提取网页链接

wen 实用脚本 28

本文目录导读:

脚本如何提取网页链接

  1. 浏览器开发者工具(手动提取)
  2. 编程脚本(高效批量提取)
  3. 浏览器插件(不写代码)
  4. 命令行工具(极简)
  5. 在线服务(免安装)
  6. 注意事项

提取网页链接的方法取决于你使用的工具或场景(如手动操作、编程、或使用现成工具),以下是几种常见的方式:

浏览器开发者工具(手动提取)

如果你是技术人员或需要少量链接,直接用浏览器最方便:

  • 复制所有链接:在网页上按 Ctrl + A(全选),Ctrl + C 复制,粘贴到记事本或Word后,链接通常保留,但会混有文本。
  • 更精准的方法:按 F12 打开开发者工具 → 点 Console(控制台),输入以下代码,回车后复制结果(会显示所有 <a> 标签的 href 属性):
    console.log([...document.querySelectorAll('a')].map(a => a.href));

    如果想只显示纯文本链接(去重、排除空链接):

    [...new Set([...document.querySelectorAll('a')].map(a => a.href).filter(href => href && !href.startsWith('javascript:')))].join('\n')

编程脚本(高效批量提取)

如果需要自动化获取大量链接,使用编程语言(Python 最常用):

使用 Python + Requests + BeautifulSoup(推荐)

import requests
from bs4 import BeautifulSoup
url = 'https://example.com'  # 替换为目标网址
headers = {'User-Agent': 'Mozilla/5.0'}  # 模拟浏览器,避免被拒
response = requests.get(url, headers=headers)
response.encoding = 'utf-8'  # 若乱码可调整
soup = BeautifulSoup(response.text, 'html.parser')
links = []
for a_tag in soup.find_all('a', href=True):
    href = a_tag['href']
    # 处理相对路径(如 /about)转为完整 URL
    if href.startswith('/'):
        href = response.url.rstrip('/') + href
    elif href.startswith('#'):
        continue  # 跳过锚点链接
    links.append(href)
# 去重并输出
unique_links = list(set(links))
for link in unique_links:
    print(link)

依赖安装pip install requests beautifulsoup4

更简单但功能较弱的:用 selenium(处理动态网页)

如果页面是 JavaScript 渲染的(如 Vue/React 单页应用),BeautifulSoup 可能抓取不到,此时用 Selenium 模拟浏览器:

from selenium import webdriver
driver = webdriver.Chrome()  # 需要安装 chromedriver
driver.get('https://example.com')
links = [elem.get_attribute('href') for elem in driver.find_elements_by_tag_name('a')]
driver.quit()
print(links)

浏览器插件(不写代码)

  • LinkClump (Chrome/Edge):按住鼠标键框选区域,自动复制该区域内所有链接。
  • Copy Links:支持一键复制当前页面所有链接(可过滤类型)。
  • DownThemAll! (Firefox):专门下载链接,也支持列表导出。

命令行工具(极简)

  • curl + grep(Linux/Mac/WSL):
    curl -s 'https://example.com' | grep -oP 'href="[^"]*"' | cut -d'"' -f2 | sort -u
  • wgetwget -O - 'https://example.com' | grep -oP 'href="[^"]*"' | cut -d'"' -f2

在线服务(免安装)

  • 使用 https://www.sitemaps.org/ 生成站点地图(需站长权限)。
  • 使用 Url Extractor 等在线工具(注意隐私,敏感网址不要用)。

注意事项

  1. 遵守 robots.txt:尊重网站的爬虫协议(如 https://example.com/robots.txt 规定的禁止爬取路径)。
  2. 频率限制:大批量提取可能被网站封 IP,建议添加延时(如 time.sleep(1))。
  3. 链接格式:部分链接可能是 JavaScript 跳转(javascript:void(0))或 ,需过滤。
  4. 相对路径:如 href="/news" 需拼接为 https://domain.com/news
  • 少量链接:浏览器控制台代码最直接。
  • 批量静态页面:Python + BeautifulSoup。
  • 动态网页:Selenium 或浏览器插件。
  • 快速上手:用 LinkClump 插件点一下即可。

如果有具体网页(公开可访问的),可以告诉我,我帮你写一个提取脚本的框架。

抱歉,评论功能暂时关闭!