爬虫 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代码中记录 a[href] 的链接,存储到将要遍历的列表;
对于已经爬取的链接,直接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()

无限增生的效果

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

相关推荐
一晌小贪欢17 小时前
Python爬虫第6课:Selenium自动化浏览器与动态内容抓取
爬虫·python·selenium·网络爬虫·python基础·python3·pathon爬虫
B站_计算机毕业设计之家2 天前
计算机毕业设计:Python农业数据可视化分析系统 气象数据 农业生产 粮食数据 播种数据 爬虫 Django框架 天气数据 降水量(源码+文档)✅
大数据·爬虫·python·机器学习·信息可视化·课程设计·农业
爬虫程序猿2 天前
把 1688 商品详情搬进 MySQL:PHP 爬虫全链路实战(2025 版)
爬虫·python·音视频
一晌小贪欢2 天前
Python爬虫第7课:多线程与异步爬虫技术
开发语言·爬虫·python·网络爬虫·python爬虫·python3
一百天成为python专家3 天前
python爬虫入门(小白五分钟从入门到精通)
开发语言·爬虫·python·opencv·yolo·计算机视觉·正则表达式
wanfeng_093 天前
python爬虫学习
爬虫·python·学习
濑户川3 天前
基于DDGS实现图片搜索,文本搜索,新闻搜索
人工智能·爬虫·python
Moniane3 天前
Web爬虫指南
爬虫·算法
深蓝电商API3 天前
快速上手 Scrapy:5 分钟创建一个可扩展的爬虫项目
爬虫·python·scrapy
直有两条腿3 天前
【爬虫】浏览器插件
爬虫