怎么用脚本获取网页所有链接

wen 实用脚本 2

本文目录导读:

怎么用脚本获取网页所有链接

  1. 方法1:浏览器控制台(最简单)
  2. 方法2:Python + BeautifulSoup
  3. 方法3:Python + Selenium(处理JavaScript渲染)
  4. 方法4:Node.js + Cheerio
  5. 方法5:命令行工具
  6. 方法6:保存到文件
  7. 注意事项

方法1:浏览器控制台(最简单)

在浏览器中按F12打开开发者工具,在Console中输入:

// 获取所有链接
const links = Array.from(document.querySelectorAll('a')).map(a => a.href);
console.log(links);
// 或者更详细的信息
const linksInfo = Array.from(document.querySelectorAll('a')).map(a => ({
    text: a.textContent.trim(),
    href: a.href, a.title,
    target: a.target
}));
console.log(linksInfo);

方法2:Python + BeautifulSoup

import requests
from bs4 import BeautifulSoup
from urllib.parse import urljoin
def get_all_links(url):
    # 发送请求
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
    }
    response = requests.get(url, headers=headers)
    response.encoding = response.apparent_encoding
    # 解析网页
    soup = BeautifulSoup(response.text, 'html.parser')
    # 获取所有链接
    links = []
    for a in soup.find_all('a', href=True):
        href = a['href']
        # 转换为绝对URL
        absolute_url = urljoin(url, href)
        links.append({
            'text': a.get_text(strip=True),
            'href': absolute_url,
            'title': a.get('title', '')
        })
    return links
# 使用示例
url = 'https://example.com'
links = get_all_links(url)
for link in links:
    print(f"文本: {link['text']}, URL: {link['href']}")

方法3:Python + Selenium(处理JavaScript渲染)

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import time
def get_links_selenium(url):
    # 配置浏览器选项
    options = Options()
    options.headless = True  # 无头模式
    # 启动浏览器
    driver = webdriver.Chrome(options=options)
    driver.get(url)
    # 等待页面加载
    time.sleep(3)
    # 获取所有链接
    links = driver.find_elements_by_tag_name('a')
    result = []
    for link in links:
        result.append({
            'text': link.text,
            'href': link.get_attribute('href'),
            'title': link.get_attribute('title')
        })
    driver.quit()
    return result
url = 'https://example.com'
links = get_links_selenium(url)
for link in links:
    print(f"文本: {link['text']}, URL: {link['href']}")

方法4:Node.js + Cheerio

const axios = require('axios');
const cheerio = require('cheerio');
async function getAllLinks(url) {
    try {
        // 获取页面
        const response = await axios.get(url, {
            headers: {
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)'
            }
        });
        // 解析HTML
        const $ = cheerio.load(response.data);
        // 提取链接
        const links = [];
        $('a').each((i, element) => {
            const link = $(element);
            links.push({
                text: link.text().trim(),
                href: link.attr('href'),
                title: link.attr('title') || ''
            });
        });
        return links;
    } catch (error) {
        console.error('Error:', error);
        return [];
    }
}
// 使用示例
getAllLinks('https://example.com').then(links => {
    links.forEach(link => {
        console.log(`文本: ${link.text}, URL: ${link.href}`);
    });
});

方法5:命令行工具

# 使用 curl 和 grep
curl -s https://example.com | grep -oP 'href="\K[^"]*'
# 使用 wget 获取所有链接
wget --spider -r -l 1 https://example.com 2>&1 | grep '^--' | awk '{ print $3 }'
# 使用 Python 一行命令
python -c "import requests; from bs4 import BeautifulSoup; [print(a.get('href')) for a in BeautifulSoup(requests.get('https://example.com').text, 'html.parser').find_all('a', href=True)]"

方法6:保存到文件

import requests
from bs4 import BeautifulSoup
from urllib.parse import urljoin
def save_links_to_file(url, output_file='links.txt'):
    response = requests.get(url)
    soup = BeautifulSoup(response.text, 'html.parser')
    with open(output_file, 'w', encoding='utf-8') as f:
        for a in soup.find_all('a', href=True):
            absolute_url = urljoin(url, a['href'])
            f.write(f"{a.get_text(strip=True)} - {absolute_url}\n")
    print(f"链接已保存到 {output_file}")
# 使用
save_links_to_file('https://example.com')

注意事项

  1. 遵守robots.txt:确保网站允许爬取
  2. 请求频率:不要过于频繁地请求,添加延迟
  3. 编码问题:设置正确的编码
  4. :如果页面有JavaScript渲染的内容,需要使用Selenium
  5. 相对路径:注意将相对路径转换为绝对URL
  6. 去重:可能需要去重处理

选择最适合您需求的方法即可,如果是简单的静态页面,使用浏览器控制台即可;如果需要程序化处理,建议使用Python方案。

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