2024-08-19



import requests
import json
import time
 
def get_data(url):
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3',
        'Accept-Encoding': 'gzip, deflate, br',
    }
    proxies = {
        "http": "http://120.0.0.1:80",
        "https": "https://120.0.0.1:443",
    }
    try:
        response = requests.get(url, headers=headers, proxies=proxies)
        if response.status_code == 200:
            return response.json()
    except requests.exceptions.RequestException as e:
        print(e)
        time.sleep(10)
 
def parse_data(data):
    results = []
    for item in data.get('data', []):
        result = {
            'title': item.get('title'),
            'url': item.get('url'),
            'source': item.get('source'),
            'published_at': item.get('published_at'),
        }
        results.append(result)
    return results
 
def save_data(data, file_path):
    with open(file_path, 'a+', encoding='utf-8') as f:
        for item in data:
            f.write(json.dumps(item, ensure_ascii=False) + '\n')
            f.flush()
 
def main():
    url = 'https://api.example.com/data'
    file_path = 'data.json'
    data = get_data(url)
    parsed_data = parse_data(data)
    save_data(parsed_data, file_path)
 
if __name__ == '__main__':
    main()

这个示例代码展示了如何使用Python进行简单的网络爬虫。它首先定义了一个获取数据的函数,使用了requests库来发送HTTP请求,并使用了代理和User-Agent来模拟浏览器行为。然后定义了一个解析数据的函数,它从响应中提取有用信息。最后,定义了一个保存数据的函数,它将解析后的数据以JSON格式保存到文件中。最后,在main函数中调用了这些函数,以完成整个爬虫的流程。

2024-08-19

Pyppeteer 是一个 Python 库,它是通过调用 Chrome 或 Chromium 浏览器的 API 来进行网页自动化的。以下是一个使用 Pyppeteer 的简单示例,该示例将使用 Pyppeteer 来访问一个网页并截屏保存。

首先,确保你已经安装了 Pyppeteer。可以通过 pip 安装:




pip install pyppeteer

以下是一个使用 Pyppeteer 的简单脚本:




import asyncio
from pyppeteer import launch
 
async def screenshot():
    browser = await launch()
    page = await browser.newPage()
    await page.goto('http://example.com')
    await page.screenshot({'path': 'example.png'})
    await browser.close()
 
asyncio.get_event_loop().run_until_complete(screenshot())

这个脚本的作用是启动一个新的浏览器实例,打开一个新页面,导航到 http://example.com 网页,然后将网页截屏并保存为当前目录下的 example.png 文件。最后关闭浏览器实例。

2024-08-19



import queue
import threading
import requests
from bs4 import BeautifulSoup
 
# 创建一个全局队列
url_queue = queue.Queue()
 
def producer(url_queue):
    """网页生产者,将新网页URL放入队列中"""
    while True:
        url = 'https://example.com/page{}'.format(url_queue.qsize() + 1)
        url_queue.put(url)
 
def consumer(url_queue):
    """网页消费者,从队列中取出URL并抓取网页内容"""
    while True:
        url = url_queue.get()
        response = requests.get(url)
        if response.status_code == 200:
            parse_html(response.text)
        url_queue.task_done()
 
def parse_html(html_content):
    """解析网页内容,提取有效信息"""
    soup = BeautifulSoup(html_content, 'html.parser')
    # 这里添加解析逻辑
    print('Parsed content:', soup.title)
 
# 启动生产者线程
producer_thread = threading.Thread(target=producer, args=(url_queue,))
producer_thread.daemon = True
producer_thread.start()
 
# 启动10个消费者线程
for _ in range(10):
    consumer_thread = threading.Thread(target=consumer, args=(url_queue,))
    consumer_thread.daemon = True
    consumer_thread.start()
 
# 等待所有任务完成
url_queue.join()

这个示例代码使用了Python的queue模块来创建一个线程安全的队列,threading模块来创建并管理线程,requests模块来发送HTTP请求,以及BeautifulSoup来解析HTML内容。这个例子中,生产者线程不断向队列中添加新的网页URL,而多个消费者线程则从队列中取出URL并抓取网页内容。这个模型是一个简单的生产者-消费者模型,适用于多线程环境中处理资源限制的任务。

2024-08-19



from fake_useragent import UserAgent
 
def get_random_user_agent():
    return UserAgent().random
 
# 使用函数获取随机的User-Agent
print(get_random_user_agent())

这段代码演示了如何使用fake_useragent库来生成一个随机的User-Agent。首先,我们导入了UserAgent类,然后定义了一个函数get_random_user_agent,该函数返回一个新的随机生成的User-Agent字符串。最后,我们打印出一个随机生成的User-Agent。这个例子简单明了地展示了如何使用这个库来满足爬虫项目中需要伪装请求身份的需求。

2024-08-19



from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
 
# 配置Selenium WebDriver
driver_path = 'chromedriver的路径'
url = '你要爬取的网站'
 
driver = webdriver.Chrome(executable_path=driver_path)
wait = WebDriverWait(driver, 20)
 
def login(username, password):
    # 登录页面的处理逻辑
    pass
 
def crawl_data():
    # 进入需要爬取数据的页面
    driver.get(url)
    
    # 这里添加页面加载等待,确保页面元素加载完成
    wait.until(EC.presence_of_element_located((By.ID, 'some_element_id')))
    
    # 开始爬取数据
    # 假设数据在table中,通过xpath定位到table
    table = driver.find_element_by_xpath('//*[@id="table_id"]')
    rows = table.find_elements_by_tag_name('tr')
    
    for row in rows:
        # 提取每一行的数据,这里根据实际情况来
        data = row.text
        print(data)
        # 保存数据到文件或数据库
 
def main():
    # 登录操作,根据实际情况进行修改
    login('your_username', 'your_password')
    
    # 开始爬取数据
    crawl_data()
 
if __name__ == "__main__":
    main()
    # 关闭浏览器
    driver.quit()

这个代码实例展示了如何使用Selenium和Python实现一个简单的定时任务网页爬虫。在这个例子中,我们首先配置了Selenium WebDriver,然后定义了一个登录函数,用于模拟登录操作。接着定义了一个爬取数据的函数,该函数会打开一个网页,等待页面加载,然后提取需要的数据。最后,在main函数中调用登录和爬取数据的函数,并在完成后关闭浏览器。这个例子提供了一个基本框架,可以根据实际需求进行扩展和修改。

2024-08-19



import requests
from bs4 import BeautifulSoup
import pandas as pd
import matplotlib.pyplot as plt
 
# 爬取数据
def crawl_data(url):
    response = requests.get(url)
    soup = BeautifulSoup(response.text, 'html.parser')
    data = soup.find_all('div', class_='price')
    prices = [int(item.text.strip()[1:]) for item in data]
    return prices
 
# 数据可视化
def visualize_data(data):
    plt.hist(data, bins=50)
    plt.title('酒店价格分布')
    plt.xlabel('价格(人民币)')
    plt.ylabel('酒店数量')
    plt.show()
 
# 数据分析和报告
def analyze_data(data):
    mean_price = pd.Series(data).mean()
    median_price = pd.Series(data).median()
    mode_price = pd.Series(data).mode()[0]
    print(f'平均价格: {mean_price}')
    print(f'中位数价格: {median_price}')
    print(f'最常见价格: {mode_price}')
 
# 主函数
def main():
    url = 'https://www.example.com/hotels'
    prices = crawl_data(url)
    analyze_data(prices)
    visualize_data(prices)
 
if __name__ == '__main__':
    main()

这个代码实例展示了如何使用Python爬取数据、进行简单的数据分析、可视化分析结果,并且提供了一个模拟的网络爬虫URL。实际应用中,你需要替换为正确的URL和相应的数据解析方法。

2024-08-19



import requests
from bs4 import BeautifulSoup
import re
import datetime
 
def get_baidu_hot_search(date):
    # 设置URL模板,其中{date}将被实际日期替换
    url_template = "https://top.baidu.com/buzz?b=1&c=31&class=3&p=1&d={date}"
    url = url_template.format(date=date)
 
    # 发送HTTP请求
    response = requests.get(url)
    response.raise_for_status()
    response.encoding = 'UTF-8'
 
    # 解析网页内容
    soup = BeautifulSoup(response.text, 'html.parser')
 
    # 使用正则表达式匹配关键词
    pattern = re.compile(r'<a href="/s?wd=(.+?)&amp;.+?>(.+?)</a>')
    matches = pattern.findall(str(soup))
 
    # 输出关键词
    hot_searches = []
    for keyword, score in matches:
        hot_searches.append({
            'keyword': keyword,
            'score': score
        })
    return hot_searches
 
# 获取今天的日期字符串
today = datetime.date.today().strftime('%Y%m%d')
# 调用函数并输出结果
hot_searches = get_baidu_hot_search(today)
for search in hot_searches:
    print(search)

这段代码使用了requests库来发送HTTP请求,使用BeautifulSoup库来解析HTML,使用正则表达式来提取关键词和热度分数。代码首先定义了一个函数get_baidu_hot_search,该函数接受日期作为参数,并返回该日期的百度热搜关键词列表。然后代码获取了今天的日期字符串,并调用函数输出结果。

2024-08-19



import requests
from bs4 import BeautifulSoup
 
def get_sub_pages(start_url):
    sub_pages = []
    response = requests.get(start_url)
    if response.status_code == 200:
        soup = BeautifulSoup(response.text, 'html.parser')
        # 假设分站的链接都在<a>标签的href属性中
        for link in soup.find_all('a'):
            url = link.get('href')
            if url.startswith('http') and 'example.com' in url:
                sub_pages.append(url)
    return sub_pages
 
def get_total_site(sub_pages):
    total_site_data = []
    for page_url in sub_pages:
        response = requests.get(page_url)
        if response.status_code == 200:
            # 这里可以添加解析每个子页面数据的逻辑
            total_site_data.append(response.text)
    return total_site_data
 
# 示例起始URL
start_url = 'http://www.example.com'
sub_pages = get_sub_pages(start_url)
total_site_data = get_total_site(sub_pages)
 
# 这里可以添加保存数据到文件或数据库的逻辑

这个代码示例展示了如何从一个起始URL开始,通过爬取该起始URL的网页内容,找出所有相关的子网页链接,并对每个子网页进行爬取,最终获取整个网站的数据。这个过程是爬虫技术中一个常见的应用场景,展示了如何从分散的页面爬取回来并整合成一个完整的数据集。

2024-08-19



import requests
from bs4 import BeautifulSoup
import time
import json
 
# 用户信息配置
USER = {
    'username': '123456789',  # 用户名
    'password': '87654321',   # 密码
    'captcha_api': 'http://api.decaptcha.com/captcha?key=YOUR_API_KEY', # 验证码API接口
}
 
# 票务信息配置
TICKET_INFO = {
    'train_date': '2023-04-01',  # 出行日期
    'from_station': 'BJP',       # 出发站
    'to_station': 'BJQ',         # 目的地站
}
 
# 登录请求头
HEADERS = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3',
    'Referer': 'https://kyfw.12306.cn/otn/resources/login.html',
}
 
# 初始化session,用于保持会话状态
session = requests.session()
 
def get_captcha():
    """获取验证码图片并返回验证码字符串"""
    resp = session.get(USER['captcha_api'])
    with open('captcha.jpg', 'wb') as f:
        f.write(resp.content)
    # 这里需要手动输入验证码,实际应用中可以集成OCR服务自动识别验证码
    captcha = input('请输入验证码:')
    return captcha
 
def login():
    """登录12306网站"""
    # 请求登录页面,获取加密参数
    resp = session.get('https://kyfw.12306.cn/otn/login/init')
    # 解析返回的HTML,获取加密参数
    soup = BeautifulSoup(resp.text, 'lxml')
    login_form = {
        'username': USER['username'],
        'password': USER['password'],  # 密码应为加密后的密码
        'appid': 'otn',
    }
    # 登录请求
    resp = session.post('https://kyfw.12306.cn/otn/login/loginAysnSuggest', data=login_form)
    print(resp.json())
 
def query_ticket():
    """查询票务信息"""
    # 构造查询参数
    query_params = {
        'leftTicketDTO.train_date': TICKET_INFO['train_date'],
        'leftTicketDTO.from_station': TICKET_INFO['from_station'],
        'leftTicketDTO.to_station': TICKET_INFO['to_station'],
        'purpose_codes': 'ADULT',
    }
    # 查询票务信息
    resp = session.post('https://kyfw.12306.cn/otn/leftTicket/queryZ', json=query_params, headers=HEADERS)
    print(resp.json())
 
def buy_ticket():
    """模拟购票流程"""
    # 此函数需要根据实际购票流程来编写,需要处理加入车厢、选择座位等步骤
    pass
 
def main():
    # 获取验证码
    captcha = get_captcha()
    # 登录
    login()
    # 查询票务信息
    query_ticket()
    # 自动购票
    buy_ticket()
 
if __name__ == '__main__':
    main()

这个示例代码提供了一个简化的框架来说

2024-08-19



import requests
import execjs
 
# 请求网页
url = 'http://example.com/path/to/page'
response = requests.get(url)
 
# 解析JS代码,找到加密函数并调用
js_code = """
function encrypt(data) {
    // 这里是加密函数的代码
    // ...
}
"""
 
# 使用execjs执行JS代码
ctx = execjs.compile(js_code)
encrypted_data = ctx.call('encrypt', 'your_data_here')
 
# 使用加密后的数据发起POST请求
post_url = 'http://example.com/path/to/post/endpoint'
post_data = {
    'encryptedField': encrypted_data
}
post_response = requests.post(post_url, data=post_data)
 
# 打印结果
print(post_response.text)

这个示例展示了如何使用Python的requests库来获取网页内容,以及如何使用execjs库来执行提供的JavaScript加密函数,并将加密后的数据用于POST请求。这是进行Web爬虫开发时了解和应用JavaScript加密的一个基本例子。