使用 Python 搜索 Craigslist 指南

评论: 0

Craigslist 仍然是当前数字场景中访问特定分类广告的重要平台。事实证明,使用 Python 从广告中提取详细信息非常有用。Python 的适应性和强大库(如 Requests 或 BeautifulSoup)可以帮助进行富有成效的网络搜索操作。本指南深入探讨了如何使用 Python 进行 Craigslist 搜索,重点介绍了如何使用 BeautifulSoup 和 Requests 进行内容提取,以及如何使用代理轮换来有效浏览反僵尸防御系统。

使用 Python 搜刮 Craigslist 的基本步骤

接下来,我们将一步一步地介绍刮擦过程,从发送 HTTP 请求和提取特定页面元素开始,到以所需格式保存数据结束。

设置环境

您需要安装必要的库:


pip install beautifulsoup4
pip install requests

向 Craigslist 页面发送 HTTP 请求

使用请求库向 Craigslist 列表页面发送 HTTP GET 请求。


import requests

# 要搜索的 Craigslist URL 列表
urls = [
    "link",
    "link"
]

for url in urls:
    # 向 URL 发送 GET 请求
    response = requests.get(url)
    
    # 检查请求是否成功(状态代码 200)
    if response.status_code == 200:
        # 从响应中提取 HTML 内容
        html_content = response.text
        
    else:
        # 如果请求失败,则打印带有状态代码的错误信息
        print(f"Failed to retrieve {url}. Status code: {response.status_code}")

使用 BeautifulSoup 解析 HTML 内容

使用 BeautifulSoup 进行 HTML 解析并浏览检索到的内容。


from bs4 import BeautifulSoup

# 遍历列表中的每个 URL
for url in urls:
    # 向 URL 发送 GET 请求
    response = requests.get(url)
    
    # 检查请求是否成功(状态代码 200)
    if response.status_code == 200:
        # 从响应中提取 HTML 内容
        html_content = response.text
        
        # 使用 BeautifulSoup 解析 HTML 内容
        soup = BeautifulSoup(html_content, 'html.parser')
        
    else:
        # 如果请求失败,则打印带有状态代码的错误信息
        print(f"Failed to retrieve {url}. Status code: {response.status_code}")

使用 BeautifulSoup 方法提取数据

使用 BeautifulSoup 方法从 Craigslist 列表中提取项目标题和价格等数据。


from bs4 import BeautifulSoup

# 遍历列表中的每个 URL
for url in urls:
    # 向 URL 发送 GET 请求
    response = requests.get(url)
    
    # 检查请求是否成功(状态代码 200)
    if response.status_code == 200:
        # 从响应中提取 HTML 内容
        html_content = response.text
        
        # 使用 BeautifulSoup 解析 HTML 内容
        soup = BeautifulSoup(html_content, 'html.parser')
        
        # 提取特定数据点
        # 查找列表标题
        title = soup.find('span', id='titletextonly').text.strip()
        
        # 查找挂牌价格
        price = soup.find('span', class_='price').text.strip()
        
        # 查找列表描述(可能包含多个段落)
        description = soup.find('section', id='postingbody').find_all(text=True, recursive=False)
        
        # 打印提取的数据(用于演示)
        print(f"Title: {title}")
        print(f"Price: {price}")
        print(f"Description: {description}")
        
    else:
        # 如果请求失败,则打印带有状态代码的错误信息
        print(f"Failed to retrieve {url}. Status code: {response.status_code}")

标题:

1.png

价格:

2.png

说明:

3.png

将刮擦的数据保存到 CSV 文件

提取数据后,将其保存为 CSV 文件,以便进一步分析或与其他工具集成。


import csv

# 定义 CSV 文件路径和字段名称
csv_file = 'craigslist_data.csv'
fieldnames = ['Title', 'Price', 'Description']

# 将数据写入 CSV 文件
try:
    # 以 UTF-8 编码的写模式打开 CSV 文件
    with open(csv_file, mode='w', newline='', encoding='utf-8') as file:
        # 用指定的字段名创建 CSV DictWriter 对象
        writer = csv.DictWriter(file, fieldnames=fieldnames)
        
        # 在 CSV 文件中写入标题行
        writer.writeheader()
        
        # 迭代搜索数据列表中的每个项目
        for item in scraped_data:
            # 将每个项目作为一行写入 CSV 文件
            writer.writerow(item)
        
    # 将数据写入 CSV 文件后打印成功信息
    print(f"Data saved to {csv_file}")

except IOError:
    # 如果在写入 CSV 文件时出现 IOError,则打印错误信息
    print(f"Error occurred while writing data to {csv_file}")

处理潜在的路障

Craigslist 可能会采取措施防止刮擦,例如 IP 屏蔽或验证码挑战。为减少这些问题,请考虑使用代理和旋转用户代理。

使用代理:

此示例演示了如何使用具有 IP 地址授权的代理。


proxies = {
    'http': 'http://your_proxy_ip:your_proxy_port',
    'https': 'https://your_proxy_ip:your_proxy_port'
}

response = requests.get(url, proxies=proxies)

用户代理轮换:


import random

user_agents = [
    'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
    'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
    # 根据需要添加更多用户代理
]

headers = {
    'User-Agent': random.choice(user_agents)
}

response = requests.get(url, headers=headers)

完整代码

这个完整的 Python 脚本展示了如何集成不同的组件来构建一个高效的 Craigslist scraper,从多个 URL 中提取、解析和检索数据。


import requests
import urllib3
from bs4 import BeautifulSoup
import csv
import random
import ssl

ssl._create_default_https_context = ssl._create_stdlib_context
urllib3.disable_warnings()


# 要搜索的 Craigslist URL 列表
urls = [
    "link",
    "link"
]

# 用户代理和代理
user_agents = [
    'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
    'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
]

proxies = [
    {'http': 'http://your_proxy_ip1:your_proxy_port1', 'https': 'https://your_proxy_ip1:your_proxy_port1'},
    {'http': 'http://your_proxy_ip2:your_proxy_port2', 'https': 'https://your_proxy_ip2:your_proxy_port2'},
]

# 用于存储刮擦数据的列表
scraped_data = []

# 循环浏览列表中的每个 URL
for url in urls:
    # 每次请求时轮流使用用户代理,以避免被检测到
    headers = {
        'User-Agent': random.choice(user_agents)
    }

    # 为每个请求使用不同的代理,以避免 IP 屏蔽
    proxy = random.choice(proxies)

    try:
        # 向 Craigslist URL 发送带标头和代理的 GET 请求
        response = requests.get(url, headers=headers, proxies=proxy, timeout=30, verify=False)
        
        # 检查请求是否成功(状态代码 200)
        if response.status_code == 200:
            # 解析响应的 HTML 内容
            html_content = response.text
            soup = BeautifulSoup(html_content, 'html.parser')

            # 从解析的 HTML 中提取数据
            title = soup.find('span', id='titletextonly').text.strip()
            price = soup.find('span', class_='price').text.strip()
            description = soup.find('section', id='postingbody').get_text(strip=True, separator='\n')  # Extracting description

            # 以字典形式在列表中添加刮擦数据
            scraped_data.append({'Title': title, 'Price': price, 'Description': description})
            print(f"Data scraped for {url}")
        else:
            # 如果请求失败,则打印错误信息
            print(f"Failed to retrieve {url}. Status code: {response.status_code}")
    except Exception as e:
        # 如果刮擦过程中出现错误,则打印异常信息
        print(f"Exception occurred while scraping {url}: {str(e)}")

# 设置 CSV 文件以存储刮擦数据
csv_file = 'craigslist_data.csv'
fieldnames = ['Title', 'Price', 'Description']

# 将搜索到的数据写入 CSV 文件
try:
    with open(csv_file, mode='w', newline='', encoding='utf-8') as file:
        writer = csv.DictWriter(file, fieldnames=fieldnames)

        # 在 CSV 文件中写入页眉行
        writer.writeheader()

        # 遍历 scraped_data 列表,并将每个项目写入 CSV 文件
        for item in scraped_data:
            writer.writerow(item)

    # 如果数据保存成功,则打印成功信息
    print(f"Data saved to {csv_file}")
except IOError:
    # 如果在写入 CSV 文件时出现 IOError,则打印错误信息
    print(f"Error occurred while writing data to {csv_file}")

Craigslist 非常重要,因为它为我们提供了一个可以找到分类广告的地方,这些广告为我们提供了考察市场、寻找线索等方面的有用信息。通过 Python 使用 BeautifulSoup 和 Request 等库,Craigslist 的网络搜刮变得非常容易。本教程讨论的关键策略是处理动态内容和旋转代理。通过负责任地使用 Python,您可以从 Craigslist 列表中提取可操作的见解,为各个领域的明智决策提供支持。

评论:

0 评论