爬虫 crawler 入门爬取不设防网页 并实现无限增生

基础版本

爬取网页后直接将前端html代码不加处理的输出

python 复制代码
# pip3 install requests
import requests

# request the target URL
def crawler():
    response = requests.get("https://www.scrapingcourse.com/ecommerce/")
    response.raise_for_status()
    print(response.text)

# execute the crawler
crawler()

无限增生的爬虫

从第一个链接开始,记录已经遍历过的链接;
并且从这个链接爬取的html代码中记录 ahref 的链接,存储到将要遍历的列表;
对于已经爬取的链接,直接continue处理

python 复制代码
# pip3 install requests
import requests

def crawler():
    while urls_to_visit:

        # get the page to visit from the list
        current_url = urls_to_visit.pop(0)
        print(current_url)
        if current_url in visited_urls:
            continue
        # 记录访问过的url到列表中
        visited_urls.add(current_url)

        try:
            response = requests.get(current_url, timeout=5)  # 设置超时时间,避免死循环
            response.raise_for_status()  # 检查请求是否成功
        except requests.RequestException as e:
            print(f"请求失败: {current_url}, 错误: {e}")
            continue

        # parse the HTML
        soup = BeautifulSoup(response.text, "html.parser")

        # collect all the links
        link_elements = soup.select("a[href]")
        for link_element in link_elements:
            url = link_element["href"]

            if url.startswith("#"):
                continue  # ignore internal links

            # convert links to absolute URLs
            if not url.startswith("http"):
                absolute_url = requests.compat.urljoin(target_url, url)
            else:
                absolute_url = url

            # ensure the crawled link belongs to the target domain and hasn't been visited
            if (
                absolute_url.startswith(target_url)
                and absolute_url not in urls_to_visit
            ):
                urls_to_visit.append(url)

# pip3 install requests beautifulsoup4

from bs4 import BeautifulSoup



target_url = "https://www.scrapingcourse.com/ecommerce/"
# initialize the list of discovered URLs
urls_to_visit = [target_url]
visited_urls = set()  # 记录已访问的 URL,防止重复爬取
# execute the crawler
crawler()

无限增生的效果

部分链接爬取失败后会返回错误信息

相关推荐
深蓝电商API5 小时前
protobuf逆向:从抓包乱码到还原数据结构
爬虫·protobuf
小静AI工程实验室16 小时前
Python 爬虫解析 JSON-LD:多块 script、@graph 与坏数据的 9 个边界
爬虫·python·json
要吃这碗饭16 小时前
YouTube 数据抓取出现 429/403 错误?2026 反爬机制拆解与爬虫选型指南
网络·爬虫·网络协议
袁袁袁袁满16 小时前
AI Agent 如何“看懂“互联网?
爬虫·python·自动化·爬虫实战·多线程爬虫
Helix25017 小时前
Python爬虫零基础实战:3步抓取网页数据并导出Excel
爬虫·python·beautifulsoup·excel·python教程·requests·网页数据
深蓝电商API2 天前
Frida入门到实战:hook so层与Java层的姿势总结
爬虫·frida
小静AI工程实验室2 天前
robots.txt 不是门禁:RFC 9309 规则、缓存与 Python 爬虫的 10 个边界
爬虫·python·缓存
远航计算机2 天前
AI 爬虫分三种,你 robots.txt 里挡的是哪一种?
人工智能·爬虫·aigc
深蓝电商API3 天前
大厂验证码对抗升级:从“破解”到“养环境”的思路转变
爬虫·验证码
Getgit3 天前
亮数据 | Browser API 实战:Booking.com 动态页面抓取对比
爬虫·亮数据·broowser api