当前位置:   article > 正文

使用 ChatGPT 代码解释器编写网络爬虫非常简单_ai相关,会使用chatgpt相关开发 数据爬虫,可以爬取抖音快手相关的发布授权以及

ai相关,会使用chatgpt相关开发 数据爬虫,可以爬取抖音快手相关的发布授权以及


请添加图片描述

OpenAI 的 ChatGPT 刚刚推出了一个名为代码解释器(code interpreter)的新功能,可以直接在聊天中运行 Python 代码。虽然 ChatGPT 目前还不能直接爬取网络,但是解释器在网络爬虫开发中非常有帮助,特别是在处理 HTML 解析时。

使用这个功能,ChatGPT 可以接收 HTML 文档,并自动找出其中的所有数据,并输出可用于网络爬取的代码。

在本教程中,我们将介绍如何使用 ChatGPT 进行 AI 网络爬虫开发。具体来说,我们将介绍如何使用 ChatGPT 解释器来编写 Python 和 BeautifulSoup 的 HTML 解析代码。我们将创建一些提示,并使用 GPT 的代码解释器功能来为我们编写网络爬取代码。

我们还将介绍一些常见的陷阱和编写提示的技巧,以获得最佳的网络爬取结果。让我们开始吧!

  1. 启用 ChatGPT 代码解释器
  2. 使用 ChatGPT 解释器进行 HTML 解析
    1. 获取示例页面
    2. 使用 ChatGPT 和 BeautifulSoup 解析 HTML
    3. 提示的后续操作
  3. 常见问题
  4. 总结

启用 ChatGPT 代码解释器

请注意,目前代码解释器仅对高级用户开放,并且需要在 OpenAI 设置中启用:

  1. 登录 ChatGPT 并选择“…”菜单以访问设置面板。
  2. 选择“Beta 功能”选项卡,启用“代码解释器”。
  3. 使用“代码解释器”功能开始一个新的 GPT4 聊天。

现在可以使用“+”按钮将文件上传到每个聊天中,ChatGPT 可以开始读取您的数据并进行编码。

ChatGPT 可以在没有代码解释器的情况下用于爬虫开发吗?

可以,但效果远不如有代码解释器时好。代码解释器的关键价值在于 GPT 执行代码并在出现错误时进行自我纠正。

例如,如果 GPT 猜测产品价格似乎在 <div class="product-price"> 元素下,但实际上并不存在,它将接受错误消息并进行新的、更好的猜测。

如果没有代码解释器,我们必须自己进行代码验证,这可能需要多次尝试和更正才能从 GPT 中获得可用的代码。这个耗时的过程违背了使用 GPT 的初衷。

使用 ChatGPT 解释器进行 HTML 解析

从爬取的页面中提取数据是网络爬取中最耗时的任务之一,现在我们可以使用 GPT 来帮助我们完成这个任务!

在爬取时,我们通常使用 HTML 解析工具,如 CSS 选择器、XPath 或 BeautifulSoup - ChatGPT 解释器都可以与这些工具一起使用。

话虽如此,目前 GPT 最适合与 beautilfulsoup4 一起使用。我们还将使用 httpx 来下载 HTML 文件。请使用 pip install 命令安装这些 Python 包以跟随本教程:

$ pip install beautifulsoup4 httpx
  • 1

获取示例页面

首先,我们需要提供一个示例页面文件给 ChatGPT 解释器。可以直接从浏览器保存(ctrl+s),或使用 wgetcurl 命令下载。

在本项目中,我们将使用 web-scraping.dev 网站上的一个示例产品页面:

$ wget https://web-scraping.dev/product/1 -O product.html
  • 1
对于无头浏览器

当使用无头浏览器(如 Puppeteer、Playwright 或 Selenium)进行爬取时,我们得到的是渲染后的 HTML 文件,而 wget 或 Python 的 requests/httpx 无法获取这些文件。

渲染后的 HTML 可能包含动态数据,在源 HTML 中不存在。如果您的爬虫可以处理这些数据,请在 GPT 的提示中使用它。

要获取网页的渲染后 HTML,最简单的方法是使用浏览器开发者工具控制台:

copy(document.body.innerHTML);
  • 1

这将把当前页面的完整渲染后 HTML 复制到剪贴板中。

提取片段

某些页面可能包含大量 HTML,这可能会降低 GPT 的响应质量。GPT 需要处理所有这些数据,数据越多,它找到正确结果的难度就越大。

在这种情况下,只保存包含要提取的数据的 HTML 部分。以下是使用 Chrome Devtools 提取 HTML 片段的示例:

使用浏览器开发者工具捕获 HTML 片段检查所需元素并直接复制其 outerhtml

使用 ChatGPT 和 BeautifulSoup 解析 HTML

准备好 HTML 文件后,我们可以开始使用 ChatGPT 进行解析。

为此,我们将使用上传了我们的示例 HTML 文件的以下提示(使用聊天中的“+”按钮上传文件):

使用 Python 和 BeautifulSoup,你能解析出这个 HTML 中的所有产品数据吗?在执行任何解析操作之前,请完整地提供所有的 HTML 文件。在解析器中假设此示例页面上的数据字段可能在其他页面上缺失,因此解析器在遇到缺失值时不应崩溃。

一些关键的提示建议:

  • 明确指出解析所有的 HTML。GPT 优化为懒加载,会尽量避免做额外的工作,这可能导致解析器出错。
  • 明确指出要使用的工具。目前,GPT 代码解释器最适合与 BeautifulSoup 及其 findfind_all 方法一起使用。
  • 如果可能,明确指出要提取的数据。如果您知道目标数据包含什么(产品名称、价格等),请列出来。

让我们试试这个提示:

GPT 对解析任务请求的响应

输出:

{'title': 'Box of Chocolate Candy',
 'description': "Indulge your sweet tooth with our Box of Chocolate Candy. Each box contains an assortment of rich, flavorful chocolates with a smooth, creamy filling. Choose from a variety of flavors including zesty orange and sweet cherry. Whether you're looking for the perfect gift or just want to treat yourself, our Box of Chocolate Candy is sure to satisfy.",
 'images': ['https://web-scraping.dev/assets/products/orange-chocolate-box-small-2.png',
  'https://web-scraping.dev/assets/products/orange-chocolate-box-small-3.png',
  'https://web-scraping.dev/assets/products/orange-chocolate-box-small-4.png'],
 'price': '$9.99',
 'price_full': '$12.99',
 'variants': [{'variant_id': 'orange-medium',
   'variant_info': 'orange, medium'},
  {'variant_id': 'orange-large', 'variant_info': 'orange, large'},
  {'variant_id': 'cherry-small', 'variant_info': 'cherry, small'},
  {'variant_id': 'cherry-medium', 'variant_info': 'cherry, medium'},
  {'variant_id': 'cherry-large', 'variant_info': 'cherry, large'}],
 'features': [{'feature': 'material', 'value': 'Premium quality chocolate'},
  {'feature': 'flavors', 'value': 'Available in Orange and Cherry flavors'},
  {'feature': 'sizes', 'value': 'Available in small, medium, and large boxes'},
  {'feature': 'brand', 'value': 'ChocoDelight'},
  {'feature': 'care instructions', 'value': 'Store in a cool, dry place'},
  {'feature': 'purpose', 'value': 'Ideal for gifting or self-indulgence'}],
 'reviews': [{'date': '2022-07-22',
   'id': 'chocolate-candy-box-1',
   'rating': 5,
   'text': 'Absolutely delicious! The orange flavor is my favorite.'},
  {'date': '2022-08-16',
   'id': 'chocolate-candy-box-2',
   'rating': 4,
   'text': 'I bought these as a gift, and they were well received. Will definitely purchase again.'},
  {'date': '2022-09-10',
   'id': 'chocolate-candy-box-3',
   'rating': 5,
   'text': 'Nice variety of flavors. The chocolate is rich and smooth.'},
  {'date': '2022-10-02',
   'id': 'chocolate-candy-box-4',
   'rating': 5,
   'text': 'The cherry flavor is amazing. Will be buying more.'},
  {'date': '2022-11-05',
   'id': 'chocolate-candy-box-5',
   'rating': 4,
   'text': 'A bit pricey, but the quality of the chocolate is worth it.'}]}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39

在这里,我们上传了示例产品的 HTML 文件,并要求 GPT 使用 BeautifulSoup 进行解析。这是它生成的解析代码:

import json

product_data = {}

# 产品标题
try:
    product_data["title"] = soup.find("h3", class_="card-title product-title").text.strip()
except AttributeError:
    product_data["title"] = None

# 产品描述
try:
    product_data["description"] = soup.find("p", class_="product-description").text.strip()
except AttributeError:
    product_data["description"] = None

# 产品图片
try:
    product_images = soup.find_all("img", class_="img-responsive product-img")
    product_data["images"] = [img["src"] for img in product_images]
except AttributeError:
    product_data["images"] = None

# 产品价格
try:
    product_data["price"] = soup.find("span", class_="product-price mt-5 fs-1 text-success").text.strip()
    product_data["price_full"] = soup.find("span", class_="product-price-full").text.strip()
except AttributeError:
    product_data["price"] = None
    product_data["price_full"] = None

# 产品变体
try:
    product_variants = soup.find_all("a", class_="variant list-group-item list-group-item-action")
    product_data["variants"] = [{"variant_id": variant["data-variant-id"], "variant_info": variant.text.strip()} for variant in product_variants]
except AttributeError:
    product_data["variants"] = None

# 产品特性
try:
    product_features = soup.find_all("tr", class_="feature")
    product_data["features"] = [{"feature": feature.find("td", class_="feature-label").text.strip(), "value": feature.find("td", class_="feature-value").text.strip()} for feature in product_features]
except AttributeError:
    product_data["features"] = None

# 产品评论
try:
    reviews_script = soup.find("script", {"id": "reviews-data"}).string
    reviews_json = json.loads(reviews_script)
    product_data["reviews"] = reviews_json
except AttributeError:
    product_data["reviews"] = None
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52

这段代码虽然不是很出色,但非常易读且可用。我们主要关注的是 soup.find() 方法,这使得它成为任何爬虫项目的绝佳起点。

如果你想从 GPT 本身获得更加优化的结果,请尝试询问:

能否将这段解析代码更加符合惯用方式,并将其抽象化以避免重复

import httpx
from bs4 import BeautifulSoup

def extract_single_item(soup, tag, attr=None, class_=None, process_func=lambda x: x):
    try:
        if attr is not None:
            element = soup.find(tag, {attr: class_})
        else:
            element = soup.find(tag, class_=class_)
        return process_func(element.text.strip())
    except AttributeError:
        return None


def extract_multiple_items(soup, tag, attr=None, class_=None, process_func=lambda x: x):
    try:
        if attr is not None:
            elements = soup.find_all(tag, {attr: class_})
        else:
            elements = soup.find_all(tag, class_=class_)
        return [process_func(element) for element in elements]
    except AttributeError:
        return None


# 产品数据提取
def scrape_product(url):
    response = httpx.get(url)
    assert response.status_code == 200
    soup = BeautifulSoup(response.text)
    return {
        "title": extract_single_item(soup, "h3", class_="card-title product-title"),
        "description": extract_single_item(soup, "p", class_="product-description"),
        "images": extract_multiple_items(soup, "img", class_="img-responsive product-img", process_func=lambda x: x["src"]),
        "price": extract_single_item(soup, "span", class_="product-price mt-5 fs-1 text-success"),
        "price_full": extract_single_item(soup, "span", class_="product-price-full"),
        "variants": extract_multiple_items(
            soup, 
            "a", 
            class_="variant list-group-item list-group-item-action", 
            process_func=lambda x: {"variant_id": x["data-variant-id"], "variant_info": x.text.strip()}
        ),
        "features": extract_multiple_items(
            soup, 
            "tr", 
            class_="feature", 
            process_func=lambda x: {"feature": x.find("td", class_="feature-label").text.strip(), "value": x.find("td", class_="feature-value").text.strip()}
        ),
        "reviews": extract_single_item(
            soup, 
            "script", 
            attr="id", 
            class_="reviews-data", 
            process_func=lambda x: json.loads(x.string)
        ),
    }

# 示例用法:
scrape_product("https://web-scraping.dev/product/1")
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59

因此,我们可以看到,通过对 GPT 进行适当引导,它能够生成易读且可持续的使用 Beautifulsoup 进行网页爬取的 HTML 解析代码。获得高质量结果的关键是提供良好的 HTML 示例和足够狭窄的提示,使 GPT 能够专注于当前任务。

提示后续操作

我们从当前提示中获得了很好的结果,但每个网页都是不同的,结果可能会有所不同。以下是一些后续提示,可以帮助您获得更好的结果:

有些数据可能位于 隐藏的网页数据 中,而不是 HTML。尝试询问是否有任何产品数据可在脚本标签或其他不可见元素中找到:

脚本标签或其他不可见元素中是否有任何产品数据可用?

某些 HTML 页面使用动态 CSS 类名,这可能会使使用 beautifulsoup 进行解析变得困难。尝试请求避免使用动态类名进行解析:

避免使用动态 CSS 类名进行解析

包含大量信息的页面可能对 GPT 进行解析来说过于复杂。尝试将解析任务分解为较小的块:

  1. 解析产品数据
  2. 解析产品评论

请记住,ChatGPT 在理解后续指令方面非常出色,因此您可以引导它生成更好的结果。稍后,可以将有效的补充内容合并到原始提示中。

常见问题解答

为了总结使用 chatgpt 代码解释器进行网页爬取的指南,让我们来看一些相关的常见问题:

使用 chatgpt 进行网页爬取是否合法?

是的,使用 chatgpt 进行 AI 网站爬虫开发是完全合法且被 OpenAI 允许的。值得注意的是,当使用 “bots” 等黑暗术语时,chatgpt 可能会抱怨协助自动化任务,因此最好尽可能详细地使用行业术语,如网页爬取。

chatgpt 能直接进行网页爬取吗?

目前,ChatGPT 代码解释器无法访问网络,因此无法自行检索示例页面。这可能会成为将来可用的功能,但目前,您需要通过文件上传功能提供 HTML 示例。

chatgpt 代码解释器是否可以帮助处理 NodeJS 或 JavaScript 爬取?

不可以。目前,ChatGPT 代码解释器不支持任何 JavaScript 执行环境。然而,这可能会成为将来的功能,因此我们建议关注像 NodeJS 和 Cheerio 这样的工具。

chatgpt 代码解释器是否可以帮助解析 JSON 数据?

是的,它可以。JSON 在网页爬取中越来越常见,通过 隐藏的网页数据 等技术,chatGPT 代码解释器可以帮助查找和解析 JSON 数据,使用本指南中描述的相同提示技巧。

总结

在这个快速教程中,我们看了一下如何使用新的 ChatGPT 代码解释器功能生成 HTML 解析代码。我们看到,通过狭窄的提示和良好的 HTML 示例,可以获得良好的结果。

虽然 ChatGPT 目前还不能令人信服地进行网页爬取,但新的代码解释器功能使其能够自我纠正和改进,使其成为启动新的 AI 动力网页爬取器的强大工具。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小蓝xlanll/article/detail/368720?site
推荐阅读
相关标签
  

闽ICP备14008679号