admin管理员组

文章数量:1532030

保存此脚本并使用 Visual Studio Code 中的 Python 运行它。您会注意到,代码启动 Chrome、导航到 Yelp、清除位置文本框、输入“斯德哥尔摩”、单击搜索按钮、过滤当前营业的商家,然后关闭页面。之后,抓取结果将保存到 Excel 文件中 stockholm_bussinsess.xlsx:随着数字经济的持续指数级增长 ,从API、网站和数据库等各种来源收集数据 比以往任何时候都更加重要。
提取数据的一种常见方法是通过 网页抓取。网页抓取涉及使用自动化工具获取网页并解析其内容以提取特定信息以供进一步分析和使用。常见用例包括市场研究、价格监控和数据聚合。
实施网络抓取涉及处理动态内容、管理会话和 Cookie、处理反抓取措施以及确保法律合规性。这些挑战需要先进的工具和技术来有效提取数据。ChatGPT 可以 利用其自然语言处理功能来生成代码和排除错误,从而帮助解决这些复杂性。
在本文中,您将学习如何使用 ChatGPT 为主要依赖静态 HTML 内容的网站以及采用更复杂的页面生成技术的复杂网站生成抓取代码。

先决条件
在开始本教程之前,请确保您已具备以下条件:
熟悉 Python
使用 Visual Studio Code在你的计算机上安装并配置 Python 环境 
ChatGPT 帐户
当您使用 ChatGPT 生成网页抓取脚本时,主要有两个步骤:
1.记录代码需要遵循的每个步骤以查找要抓取的信息,例如要定位的 HTML 元素、要填充的文本框以及要单击的按钮。通常,您需要复制特定的 HTML 元素选择器。为此,右键单击要抓取的特定页面元素,然后单击 检查;Chrome 会突出显示特定的 DOM 元素。右键单击它并选择 复制 > 复制选择器 ,以便将 HTML 选择器路径复制到剪贴板:

2.制作具体、详细的 ChatGPT 提示来生成抓取代码。
3.执行并测试生成的代码。

使用 ChatGPT 抓取静态 HTML 网站

现在您已经熟悉了一般的工作流程,让我们使用 ChatGPT 来抓取一些包含 静态 HTML 元素的网站。首先,您将从 https://books.toscrape抓取图书标题和价格。

首先,您需要确定包含所需数据的 HTML 元素:

接下来,您需要编写具体且详细的 ChatGPT 提示来生成抓取代码。为此,您需要告诉 ChatGPT 安装任何所需的 Python 包,引导它提取 HTML 选择器(您之前已确定),然后要求它将数据保存为 Excel 文件.

  • 这本书的书名选择器  是 #default > div.container-fluid.page > div > div > div > section > div:nth-child(2) > ol > li:nth-child(1) > article > h3 > a
  • 书价的选择器是  * #default > div.container-fluid.page > div > div > div > section > div:nth-child(2) > ol > li:nth-child(1) > article > div.product_price > p.price_color

    使用 ChatGPT 抓取静态 HTML 网站

    现在您已经熟悉了一般的工作流程,让我们使用 ChatGPT 来抓取一些包含 静态 HTML 元素的网站。首先,您将从 https://books.toscrape抓取图书标题和价格。

    首先,您需要确定包含所需数据的 HTML 元素:

  • 这本书的书名选择器  是 #default > div.container-fluid.page > div > div > div > section > div:nth-child(2) > ol > li:nth-child(1) > article > h3 > a
  • 书价的选择器是  * #default > div.container-fluid.page > div > div > div > section > div:nth-child(2) > ol > li:nth-child(1) > article > div.product_price > p.price_color

 

您可以在 ChatGPT 中输入类似这样的内容:

 您是使用Python 的 Beautiful Soup库和任何必要的自动化工具进行网络抓取的专家 。我希望您生成一个详细的分步脚本来抓取 https://books.toscrape;请执行以下操作:
安装任何必要的 Python 包。
提取书名(带有HTML选择器 #default > div.container-fluid.page > div > div > div > section > div:nth-child(2) > ol > li:nth-child(1) > article > h3 > a)和书价(只有数字,没有其他内容)(带有选择器)  #default > div.container-fluid.page > div > div > div > section > div:nth-child(2) > ol > li:nth-child(1) > article > div.product_price > p.price_color。
提取所有书名和价格的列表并将其存储在 Excel 文件中。
仅抓取第一页。
请注意: 您可能会收到略有不同的答复。

在响应中,ChatGPT 指示您运行以下命令来安装执行网页抓取的 Beautiful Soup 库和 将数据存储为 Excel 的综合数据分析库pandas 库:

<span style="color:#303b45"><span style="background-color:#ffffff"><span style="color:#71e5fe"><code class="language-none">pip3 install requests beautifulsoup4 pandas openpyxl</code></span></span></span>

您会注意到 ChatGPT 还建议安装 openpyxl,但这里不需要。

ChatGPT 还提供以下网页抓取代码:

<span style="color:#303b45"><span style="background-color:#ffffff"><span style="color:#71e5fe"><code class="language-none">import requests
from bs4 import BeautifulSoup
import pandas as pd

# URL of the website
url = 'https://books.toscrape'

# Send a GET request to the website
response = requests.get(url)
if response.status_code == 200:
    # Parse the HTML content of the page
    soup = BeautifulSoup(response.content, 'html.parser')

    # Initialize lists to store the titles and prices
    book_titles = []
    book_prices = []

    # Extract the first book title and price using the provided selectors
    book_title_selector = "#default > div.container-fluid.page > div > div > div > section > div:nth-child(2) > ol > li:nth-child(1) > article > h3 > a"
    book_price_selector = "#default > div.container-fluid.page > div > div > div > section > div:nth-child(2) > ol > li:nth-child(1) > article > div.product_price > p.price_color"

    title_element = soup.select_one(book_title_selector)
    price_element = soup.select_one(book_price_selector)

    if title_element and price_element:
        book_titles.append(title_element.get('title'))
        book_prices.append(price_element.text.strip()[1:])

    # Extract all book titles and prices on the first page
    books = soup.select('section > div:nth-child(2) > ol > li')
    for book in books:
        title = book.select_one('h3 > a')
        price = book.select_one('div.product_price > p.price_color')
        if title and price:
            book_titles.append(title.get('title'))
            book_prices.append(price.text.strip()[1:])

    # Create a DataFrame from the lists
    df = pd.DataFrame({
        'Title': book_titles,
        'Price': book_prices
    })

    # Save the DataFrame to an Excel file
    df.to_excel('books_scraped.xlsx', index=False)

    print('Data has been successfully scraped and saved to books_scraped.xlsx')
else:
    print('Failed to retrieve the webpage')</code></span></span></span>
此代码导入了 requests 模块,该模块对其抓取的网站执行 HTTP 调用。它还导入了 pandas 包,用于将抓取的数据存储在 Excel 文件中。该代码定义了网站的基本 URL 以及它所针对的特定 HTML 选择器,以获取请求的数据。

然后,代码调用网站并将网站内容作为 BeautifulSoup 名为的对象 soup。代码使用 HTML 选择器从对象中选择书名和价格的值作为列表 soup 。最后,代码根据书名和价格表创建一个 pandas DataFrame 并将其保存为 Excel 文件。

接下来,您需要将代码保存到名为的文件中 ,然后 从命令行 books_scraping.py 运行该命令 。此代码 在与相同的目录中 生成一个名为的 Excel 文件:python3 books_scraping.pybooks_scraped.xlsxbooks_scraping.py

现在您已经了解了一个示例,让我们更进一步地了解本教程并抓取另一个简单的网站:https://quotes.toscrape,其中包含一系列引文。

再次,让我们首先确定步骤的顺序。

如果您使用的是 Chrome,请找到以下 HTML 选择器:

  • body > div.container > div:nth-child(2) > div.col-md-8 > div:nth-child(1) > span.text 抓取 引文
  • body > div.container > div:nth-child(2) > div.col-md-8 > div:nth-child(1) > span:nth-child(2) > small 识别 作者

一旦确定了要抓取的 HTML 选择器,您就可以起草一个详细的提示(如下所示)来生成抓取代码:

您是使用 Python 的 Beautiful Soup 库和任何必要的自动化工具进行网络抓取的专家。我希望您能生成一个详细的分步脚本来抓取 https://quotes.toscrape。请执行以下操作:

1.安装任何必要的 Python 包。
2.提取带有 HTML 选择器 的引文 body > div.container > div:nth-child(2) > div.col-md-8 > div:nth-child(1) > span.text,以及带有选择器的作者姓名 body > div.container > div:nth-child(2) > div.col-md-8 > div:nth-child(1) > span:nth-child(2) > small。
3.提取所有引文和作者的列表并将其存储在 Excel 文件中。
4.仅抓取第一页。
输入这些信息后,ChatGPT 应该会为您提供以下命令,该命令会安装 Beautiful Soup、pandas 和 openpyxl 库:

<span style="color:#303b45"><span style="background-color:#ffffff"><span style="color:#71e5fe"><code class="language-none">pip3 install requests beautifulsoup4 pandas openpyxl</code></span></span></span>
ChatGPT 还应提供以下网页抓取代码:
<span style="color:#303b45"><span style="background-color:#ffffff"><span style="color:#71e5fe"><code class="language-none">import requests
from bs4 import BeautifulSoup
import pandas as pd

# Step 1: Fetch the web page content
url = "https://quotes.toscrape"
response = requests.get(url)
html_content = response.text

# Step 2: Parse the HTML content using BeautifulSoup
soup = BeautifulSoup(html_content, 'html.parser')

# Step 3: Extract the specific quote and author
quote_selector = "body > div.container > div:nth-child(2) > div.col-md-8 > div:nth-child(1) > span.text"
author_selector = "body > div.container > div:nth-child(2) > div.col-md-8 > div:nth-child(1) > span:nth-child(2) > small"

specific_quote = soup.select_one(quote_selector).get_text()
specific_author = soup.select_one(author_selector).get_text()

print(f"Specific Quote: {specific_quote}")
print(f"Specific Author: {specific_author}")

# Step 4: Extract all quotes and authors
quotes = soup.find_all('div', class_='quote')

all_quotes = []
for quote in quotes:
  text = quote.find('span', class_='text').get_text()
  author = quote.find('small', class_='author').get_text()
  all_quotes.append({"quote": text, "author": author})

# Step 5: Save the quotes to an Excel file
df = pd.DataFrame(all_quotes)
df.to_excel('quotes.xlsx', index=False)

print("Quotes have been saved to quotes.xlsx")
soup = BeautifulSoup(html_content, 'html.parser')

# Step 3: Extract the specific quote and author
quote_selector = "body > div.container > div:nth-child(2) > div.col-md-8 > div:nth-child(1) > span.text"
author_selector = "body > div.container > div:nth-child(2) > div.col-md-8 > div:nth-child(1) > span:nth-child(2) > small"

specific_quote = soup.select_one(quote_selector).get_text()
specific_author = soup.select_one(author_selector).get_text()

print(f"Specific Quote: {specific_quote}")
print(f"Specific Author: {specific_author}")

# Step 4: Extract all quotes and authors
quotes = soup.find_all('div', class_='quote')

all_quotes = []
for quote in quotes:
    text = quote.find('span', class_='text').get_text()
    author = quote.find('small', class_='author').get_text()
    all_quotes.append({"quote": text, "author": author})

# Step 5: Save the quotes to an Excel file
df = pd.DataFrame(all_quotes)
df.to_excel('quotes.xlsx', index=False)

print("Quotes have been saved to quotes.xlsx")</code></span></span></span>
将此代码保存到名为 的文件中 ,然后 从命令行 quotes_scraping.py 运行该命令 。此代码 在与 相同的目录中 生成一个名为 的 Excel 文件。打开生成的 Excel 文件,它应如下所示:python3 books_scraping.pyquotes_scraped.xlsxquotes_scraping.py

 

爬取复杂网站

抓取复杂网站可能具有挑战性,因为动态内容通常通过 JavaScript 加载,而 JavaScript 等工具 requests 无法 BeautifulSoup 处理这些内容。这些网站可能需要单击按钮或滚动鼠标等交互才能访问所有数据。为了应对这一挑战,您可以使用 WebDriver,它可以像浏览器一样呈现页面并模拟用户交互,确保所有内容都可以像普通用户一样访问。

例如,  Yelp 是一个面向企业的众包评论网站。Yelp 依赖于动态页面生成,需要模拟多个用户交互。在这里,您将使用 ChatGPT 生成一个抓取代码,该代码可检索斯德哥尔摩的企业列表及其评分。

要抓取 Yelp,我们首先记录一下要遵循的步骤:

  1. 找到脚本将使用的位置文本框的选择器;在本例中为 #search_location。在位置搜索框中输入“斯德哥尔摩”,然后找到搜索按钮选择器;在本例中为 #header_find_form > div.y-css-1iy1dwt > button。点击搜索按钮查看搜索结果。这可能需要几秒钟。找到包含企业名称的选择器( #main-content > ul > li:nth-child(3) > div.container_\_09f24_\_FeTO6.hoverable_\_09f24_\__UXLO.y-css-way87j > div > div.y-css-cxcdjj > div:nth-child(1) > div.y-css-1iy1dwt > div:nth-child(1) > div > div > h3 > a):
  2. 查找包含该业务评级的选择器( #main-content > ul > li:nth-child(3) > div.container_\_09f24_\_FeTO6.hoverable_\_09f24_\__UXLO.y-css-way87j > div > div.y-css-cxcdjj > div:nth-child(1) > div.y-css-1iy1dwt > div:nth-child(2) > div > div > div > div.y-css-ohs7lg > span.y-css-jf9frv): 
  3. 找到“立即打开”按钮的选择器  ;这里是 #main-content > div.stickyFilterOnSmallScreen_\_09f24_\_UWWJ3.hideFilterOnLargeScreen_\_09f24_\_ilqIP.y-css-9ze9ku > div > div > div > div > div > span > button:nth-child(3) > span
  4. 保存网页的副本,以便稍后上传,同时保存 ChatGPT 提示,以帮助 ChatGPT 理解提示的上下文。在 Chrome 中,您可以通过单击右上角的三个点,然后单击 保存并共享 > 另存页面为来执行此操作:

    接下来,使用之前提取的选择器值,你需要起草一个详细的提示来指导 ChatGPT 生成抓取脚本

    您是网页抓取专家。我希望您抓取 https://www.yelp/ 以提取特定信息。抓取前请遵循以下步骤:

    1.使用选择器清除该框 #search_location。
    2.使用选择器在搜索框中输入“斯德哥尔摩”  #search_location。
    3.单击带有选择器的按钮 #header_find_form > div.y-css-1iy1dwt > button。
    4.考虑页面加载搜索结果需要几秒钟的时间。
    5.点击带有选择器的“ 立即开始”按钮 ,#main-content > div.stickyFilterOnSmallScreen_\_09f24_\_UWWJ3.hideFilterOnLargeScreen_\_09f24_\_ilqIP.y-css-9ze9ku > div > div > div > div > div > span > button:nth-child(3) > span可以筛选现在开业的企业。
    6.创建一个包含企业名称的列表;企业名称具有选择器 #main-content > ul > li:nth-child(3) > div.container_\_09f24_\_FeTO6.hoverable_\_09f24_\__UXLO.y-css-way87j > div > div.y-css-cxcdjj > div:nth-child(1) > div.y-css-1iy1dwt > div:nth-child(1) > div > div > h3 > a。
    7.创建一个包含业务评论的列表;评论有选择器 #main-content > ul > li:nth-child(3) > div.container_\_09f24_\_FeTO6.hoverable_\_09f24_\__UXLO.y-css-way87j > div > div.y-css-cxcdjj > div:nth-child(1) > div.y-css-1iy1dwt > div:nth-child(2) > div > div > div > div.y-css-ohs7lg > span.y-css-jf9frv。
    8.创建一个包含公司名称及其评论的 Excel 文件。
    9.确保安装所有相关的 Python 包。
    10使用 Selenium 中的 WebDriver 来自动化该过程。
    11.请参阅附件的结果 HTML 页面副本,以了解有关 HTML 格式的背景信息。

    输入这些信息后,ChatGPT 会提示你安装支持 WebDriver 和 pandas 的 Web 自动化框架 Selenium:

    <span style="color:#303b45"><span style="background-color:#ffffff"><span style="color:#71e5fe"><code class="language-none">pip3 install selenium pandas</code></span></span></span>
    ChatGPT 还为您提供了一些抓取代码以及解释:保存此脚本并使用 Visual Studio Code 中的 Python 运行它。您会注意到,代码启动 Chrome、导航到 Yelp、清除位置文本框、输入“斯德哥尔摩”、单击搜索按钮、过滤当前营业的商家,然后关闭页面。之后,抓取结果将保存到 Excel 文件中 stockholm_bussinsess.xlsx:
    <span style="color:#303b45"><span style="background-color:#ffffff"><span style="color:#71e5fe"><code class="language-none">from selenium import webdriver
    from selenium.webdrivermon.by import By
    from selenium.webdrivermon.keys import Keys
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC
    import pandas as pd
    import time
    
    # Initialize the WebDriver
    driver = webdriver.Chrome()
    
    try:
        # Open Yelp
        driver.get('https://www.yelp/')
    
        # Clear the location search box
        location_box = driver.find_element(By.CSS_SELECTOR, '#search_location')
        location_box.clear()
    
        # Enter "Stockholm" in the location search box
        location_box.send_keys('Stockholm')
    
        # Click the search button
        search_button = driver.find_element(By.CSS_SELECTOR, '#header_find_form > div.y-css-1iy1dwt > button')
        search_button.click()
    
        # Wait for search results to load
        WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.CSS_SELECTOR, '#main-content'))
        )
    
        # Click on "Open Now" filter
        open_now_button = driver.find_element(By.CSS_SELECTOR, '#main-content > div.stickyFilterOnSmallScreen__09f24__UWWJ3.hideFilterOnLargeScreen__09f24__ilqIP.y-css-9ze9ku > div > div > div > div > div > span > button:nth-child(3) > span')
        open_now_button.click()
    
        # Wait for the filter results to load
        time.sleep(5)
    
        # Extract business names and reviews
        business_names = []
        business_reviews = []
    
        businesses = driver.find_elements(By.CSS_SELECTOR, '#main-content > ul > li')
    
        for business in businesses:
            try:
                name = business.find_element(By.CSS_SELECTOR, 'div.container__09f24__FeTO6.hoverable__09f24___UXLO.y-css-way87j > div > div.y-css-cxcdjj > div:nth-child(1) > div.y-css-1iy1dwt > div:nth-child(1) > div > div > h3 > a').text
                review = business.find_element(By.CSS_SELECTOR, 'div.container__09f24__FeTO6.hoverable__09f24___UXLO.y-css-way87j > div > div.y-css-cxcdjj > div:nth-child(1) > div.y-css-1iy1dwt > div:nth-child(2) > div > div > div > div.y-css-ohs7lg > span.y-css-jf9frv').text
                business_names.append(name)
                business_reviews.append(review)
            except Exception as e:
                print(f"Error extracting data for a business: {e}")
    
        # Create a DataFrame and save to Excel
        df = pd.DataFrame({'Business Name': business_names, 'Reviews': business_reviews})
        df.to_excel('stockholm_businesses.xlsx', index=False)
        print("Data saved to stockholm_businesses.xlsx")
    
    finally:
        # Close the WebDriver
        driver.quit()</code></span></span></span>

 保存此脚本并使用 Visual Studio Code 中的 Python 运行它。您会注意到,代码启动 Chrome、导航到 Yelp、清除位置文本框、输入“斯德哥尔摩”、单击搜索按钮、过滤当前营业的商家,然后关闭页面。之后,抓取结果将保存到 Excel 文件中 stockholm_bussinsess.xlsx:

 

本教程的所有源代码均可在 GitHub上找到。

结论

在本教程中,您学习了如何使用 ChatGPT 从具有静态 HTML 渲染的网站以及具有动态页面生成、外部 JavaScript 链接和用户交互的更复杂的网站中提取特定信息。

虽然抓取 Yelp 这样的网站很简单,但实际上,抓取复杂的 HTML 结构的网站可能很有挑战性,而且您可能会遇到 IP 禁令和 CAPTCHA。

为了简化操作,  Bright Data 提供各种数据收集服务,包括帮助绕过 IP 禁令的高级代理服务、用于绕过和解决 CAPTCHA 的 Web Unlocker、用于自动数据提取的Web Scraping API以及 用于高效数据提取的Scraping Browser 。

 

本文标签: 网页指南chatGPT