爬虫 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()

无限增生的效果

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

相关推荐
TLuoQiu11 小时前
小电视视频内容获取GUI工具
爬虫·python
麦麦大数据20 小时前
F004 新闻可视化系统爬虫更新数据+ flask + mysql架构
爬虫·mysql·flask·可视化·新闻
python-行者20 小时前
akamai鼠标轨迹
爬虫·python·计算机外设·akamai
NEUMaple2 天前
python爬虫(四)----requests
开发语言·爬虫·python
电商API_180079052472 天前
大规模调用淘宝商品详情 API 的分布式请求调度实践
服务器·数据库·分布式·爬虫
小白学大数据2 天前
1688商品数据抓取:Python爬虫+动态页面解析
爬虫·python·okhttp
forestsea2 天前
Nginx蜘蛛请求智能分流:精准识别爬虫并转发SEO渲染服务
运维·爬虫·nginx
华科云商xiao徐2 天前
突破Python性能墙:关键模块C++化的爬虫优化指南
c++·爬虫·python
guidovans2 天前
基于大语言模型的爬虫数据清洗与结构化
人工智能·爬虫·语言模型·自然语言处理
憨憨の大鸭鸭2 天前
python爬虫学习(2)
爬虫·学习