2024-08-18

以下是一个简单的Python爬虫示例,用于爬取微博热搜数据,并保存为HTML格式文件:




import requests
from bs4 import BeautifulSoup
 
# 设置请求头,模拟浏览器访问
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'
}
 
# 微博热搜索页面URL
url = 'https://s.weibo.com/top/summary'
 
# 发送GET请求
response = requests.get(url, headers=headers)
 
# 检查请求是否成功
if response.status_code == 200:
    # 使用BeautifulSoup解析响应内容
    soup = BeautifulSoup(response.text, 'html.parser')
    
    # 找到包含热搜数据的HTML元素
    hot_search_items = soup.find_all('div', class_='td')
    
    # 创建一个空的字符串用于存储HTML内容
    html_content = ''
    
    # 遍历所有热搜数据,构建HTML格式
    for item in hot_search_items:
        # 提取热搜词汇和指定内容
        hot_search_content = item.find('a').text
        hot_search_href = item.find('a')['href']
        hot_search_count = item.find_all('span')[1].text.strip()
        
        # 构建HTML字符串
        html_content += f'<div><a href="{hot_search_href}">{hot_search_content}</a> {hot_search_count}</div>'
    
    # 保存HTML内容到文件
    with open('weibo_hot_search.html', 'w', encoding='utf-8') as file:
        file.write(html_content)
        print('HTML文件已保存。')
else:
    print('请求失败')

这段代码首先设置了请求头,以模拟浏览器访问,然后发送GET请求到微博热搜页面。成功获取页面内容后,使用BeautifulSoup解析页面,提取热搜数据,并构建HTML格式。最后,将这些数据保存到一个HTML文件中。这个过程展示了如何使用Python爬取网页数据并进行简单的数据处理,是学习网络爬虫的一个基本入门示例。

2024-08-18

在Python爬虫技术第14节中,我们通常会使用BeautifulSoup库来解析HTML结构。以下是一个简单的例子,展示了如何使用BeautifulSoup来查找和提取HTML元素。




from bs4 import BeautifulSoup
 
# 假设我们有以下HTML内容
html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title"><b>The Dormouse's story</b></p>
<div class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</div>
<p class="story">...</p>
"""
 
# 使用BeautifulSoup解析HTML
soup = BeautifulSoup(html_doc, 'html.parser')
 
# 查找所有的<a>标签
for link in soup.find_all('a'):
    print(link.get('href'))
 
# 查找id为"link3"的<a>标签
link3 = soup.find(id='link3')
print(link3.get('href'))
 
# 查找所有class为"sister"的<a>标签的链接文字
for sister in soup.find_all('a', class_='sister'):
    print(sister.get_text())

这段代码首先导入了BeautifulSoup类,然后使用一个HTML字符串初始化了一个BeautifulSoup对象。接下来,我们使用find_all方法查找所有的<a>标签,并打印它们的href属性。我们也找到了id为link3<a>标签,并打印了它的href属性。最后,我们遍历所有class为sister<a>标签,打印它们的文本内容。这个例子展示了如何使用BeautifulSoup来进行基本的HTML结构解析和数据提取。

2024-08-18



import requests
from bs4 import BeautifulSoup
 
def get_html(url):
    """
    获取网页的HTML内容
    :param url: 网页的URL
    :return: HTML内容
    """
    try:
        response = requests.get(url)
        if response.status_code == 200:
            return response.text
        else:
            return None
    except requests.RequestException:
        return None
 
def parse_html(html):
    """
    解析HTML内容,提取博客标题和链接
    :param html: HTML内容
    :return: 博客标题和链接的字典
    """
    soup = BeautifulSoup(html, 'html.parser')
    articles = soup.find_all('article', class_='post')
    blogs = []
    for article in articles:
        blog = {
            'title': article.h2.a.text.strip(),
            'link': article.h2.a['href']
        }
        blogs.append(blog)
    return blogs
 
def save_to_file(blogs, file_path):
    """
    将博客数据保存到文件
    :param blogs: 博客数据列表
    :param file_path: 文件路径
    :return: None
    """
    with open(file_path, 'w', encoding='utf-8') as file:
        for blog in blogs:
            file.write(f"标题: {blog['title']}, 链接: {blog['link']}\n")
 
def main():
    url = 'https://blog.csdn.net/weixin_43941079'
    html = get_html(url)
    if html:
        blogs = parse_html(html)
        save_to_file(blogs, 'csdn_blogs.txt')
        print("爬取成功,结果已保存到 csdn_blogs.txt 文件。")
    else:
        print("网页获取失败。")
 
if __name__ == '__main__':
    main()

这段代码实现了从CDSN博客主页获取博客列表的功能,并将结果保存到文本文件中。代码中定义了获取HTML内容、解析HTML和保存数据到文件的函数,并在main函数中调用它们。使用了requests库来获取网页内容,BeautifulSoup来解析HTML,以及Python的文件操作来保存数据。

2024-08-18

题目描述:

给定一个由无符号整数组成的数组,数组中的值构成一个数字流。写一个函数,如果数字流中存在连续的三个数值,它们的和为0,则返回true。

解决方案:

这个问题可以通过遍历数组并检查每三个连续的数值来解决。如果它们的和为0,则返回true。否则,继续遍历直到找到一组符合条件的数值或遍历结束。

以下是各种语言的解决方案:

Java:




public class Main {
    public static void main(String[] args) {
        int[] data = {1, -2, 3, -4, 5};
        System.out.println(containsZeroSumTriplet(data));
    }
 
    public static boolean containsZeroSumTriplet(int[] data) {
        for (int i = 0; i < data.length - 2; i++) {
            for (int j = i + 1; j < data.length - 1; j++) {
                if ((data[i] + data[j] + data[j + 1]) == 0) {
                    return true;
                }
            }
        }
        return false;
    }
}

JavaScript:




function containsZeroSumTriplet(data) {
    for (let i = 0; i < data.length - 2; i++) {
        for (let j = i + 1; j < data.length - 1; j++) {
            if ((data[i] + data[j] + data[j + 1]) === 0) {
                return true;
            }
        }
    }
    return false;
}
 
let data = [1, -2, 3, -4, 5];
console.log(containsZeroSumTriplet(data));

Python:




def contains_zero_sum_triplet(data):
    for i in range(len(data) - 2):
        for j in range(i + 1, len(data) - 1):
            if data[i] + data[j] + data[j + 1] == 0:
                return True
    return False
 
data = [1, -2, 3, -4, 5]
print(contains_zero_sum_triplet(data))

C:




#include <stdio.h>
 
int containsZeroSumTriplet(int data[], int length) {
    for (int i = 0; i < length - 2; i++) {
        for (int j = i + 1; j < length - 1; j++) {
            if (data[i] + data[j] + data[j + 1] == 0) {
                return 1;
            }
        }
    }
    return 0;
}
 
int main() {
    int data[] = {1, -2, 3, -4, 5};
    printf("%d\n", containsZeroSumTriplet(data, 5));
    return 0;
}

C++:




#include <iostream>
#include <vector>
 
bool containsZeroSumTriplet(const std::vector<int>& data) {
    for (size_t i = 0; i < data.size() - 2; i++) {
        for (size_t j = i + 1; j < data.size() - 1; j++) {
            if ((data[i] + data[j] + data[j + 1]) == 0) {
                return
2024-08-17

浅拷贝(copy):拷贝父对象,不会拷贝对象内部的子对象。

深拷贝(deepcopy):拷贝父对象以及对象内部的子对象。

浅拷贝示例:




import copy
 
original_list = [1, 2, [3, 4]]
shallow_copy = copy.copy(original_list)
 
original_list[2][0] = "changed"
 
print(original_list)  # 输出: [1, 2, ['changed', 4]]
print(shallow_copy)   # 输出: [1, 2, ['changed', 4]]

深拷贝示例:




import copy
 
original_list = [1, 2, [3, 4]]
deep_copy = copy.deepcopy(original_list)
 
original_list[2][0] = "changed"
 
print(original_list)  # 输出: [1, 2, ['changed', 4]]
print(deep_copy)      # 输出: [1, 2, [3, 4]]

在深拷贝中,原始列表中的子列表没有被改变,而在浅拷贝中原始列表中的子列表被改变了。

2024-08-17

PyTorch版本、Python版本和pytorch\_lightning版本之间有相互关联,并且它们必须相互兼容才能正常工作。为了保证环境的稳定性和代码的正常运行,最好参考它们的官方文档或GitHub的release notes来选择合适的版本组合。

以下是一个简单的版本匹配指南,它提供了一个基本的指导原则,但请务必查看最新的官方文档,因为这些库可能会不断更新,并且版本兼容性可能会有变化。




PyTorch版本:
   1.x 兼容 Python 2.7, 3.5, 3.6, 3.7
   1.x 不兼容 Python 3.8+
   2.x 不兼容 Python 2.7
   2.x 兼容 Python 3.6, 3.7, 3.8, 3.9
 
Python版本:
   通常,PyTorch 1.x 兼容 Python 2.7 和 3.6+,而 PyTorch 2.x 兼容 Python 3.6 及以上版本。
 
pytorch_lightning版本:
   请参考 pytorch_lightning 的官方release notes,查看支持的PyTorch版本和Python版本。

在安装时,你应该选择与你的Python和PyTorch版本兼容的pytorch\_lightning版本。例如,如果你使用的是Python 3.8和PyTorch 1.x,那么你不能安装最新版本的pytorch\_lightning,因为它可能不支持这些版本。

为了找到合适的版本组合,你可以使用pip进行安装,指定版本号:




pip install pytorch_lightning==x.y.z
pip install torch==1.x

或者,如果你使用的是Python 3.8和PyTorch 2.x:




pip install pytorch_lightning==x.y.z
pip install torch==2.x

请替换x.y.z为你选择的pytorch\_lightning版本号。始终参考官方文档获取最新和最准确的版本信息。

2024-08-17



from flask import Flask, render_template, request, redirect, url_for
 
app = Flask(__name__)
 
# 假设这是一个简单的用户模型
users = {'admin': 'password123'}
 
@app.route('/')
def index():
    return render_template('index.html')
 
@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        if username and password and username in users and users[username] == password:
            return redirect(url_for('index'))
        return '登录失败'
    return render_template('login.html')
 
if __name__ == '__main__':
    app.run(debug=True)

这段代码展示了如何使用Flask框架创建一个简单的登录系统。在这个例子中,我们使用了一个简单的用户字典来存储用户名和密码,并且在登录时进行了验证。如果用户名和密码正确,用户将被重定向到首页;如果登录失败,则会显示错误消息。这个例子教会开发者如何处理表单数据、重定向以及如何在Flask中使用模板。

2024-08-17

由于原代码已经非常完整,这里只提供关键函数的实现和注释。




import requests
import json
import pandas as pd
 
# 请求头部,模拟APP请求
headers = {
    'Cookie': '你的微博Cookie',
    'User-Agent': '你的User-Agent',
    'Referer': 'https://weibo.com/',
}
 
# 获取微博用户信息
def get_user_info(user_id):
    url = f'https://weibo.com/p/100505{user_id}/info?is_search=0&visible=0&is_tag_user=0'
    response = requests.get(url, headers=headers)
    if response.status_code == 200:
        data = response.json()
        return {
            'user_id': user_id,
            'name': data['data']['user']['name'],
            'gender': data['data']['user']['gender'],
            'description': data['data']['user']['description'],
            'follows_count': data['data']['user']['follows_count'],
            'fans_count': data['data']['user']['fans_count'],
            'weibo_count': data['data']['user']['weibo_count'],
        }
    else:
        return None
 
# 获取微博用户信息并保存到CSV
def save_user_info_to_csv(user_id):
    user_info = get_user_info(user_id)
    if user_info:
        df = pd.DataFrame([user_info])
        df.to_csv('user_info.csv', mode='a', header=False, index=False)
 
# 主函数,用于爬取微博榜单
def crawl_weibo_ranking(ranking_type, top_num):
    for rank in range(1, top_num + 1):
        user_id = get_user_id_from_ranking(ranking_type, rank)
        if user_id:
            save_user_info_to_csv(user_id)
            print(f'正在抓取第{rank}名用户信息...')
 
# 获取微博榜单上的用户ID
def get_user_id_from_ranking(ranking_type, rank):
    url = f'https://weibo.com/p/100505{ranking_type}/ranklist?topnav=1&rank={rank}&is_search=0&visible=0&is_tag_user=0'
    response = requests.get(url, headers=headers)
    if response.status_code == 200:
        data = response.json()
        return data['data']['user']['id']
    else:
        return None
 
# 调用函数爬取微博榜单,例如:热门榜单
crawl_weibo_ranking('hot', 100)

这段代码提供了两个关键函数:get_user_infosave_user_info_to_csvget_user_info 函数负责请求微博用户的个人信息页面,并解析返回的数据。save_user_info_to_csv 函数则负责将用户信息保存到CSV文件中。这两个函数是爬取微博榜单的基础,并且演示了如何使用Python进行网络请求和数据解析。

2024-08-17



import requests
 
def get_huawei_interview_questions(url):
    headers = {
        'User-Agent': 'Mozilla/5.0',
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
        'Accept-Language': 'en',
        'Connection': 'keep-alive',
    }
    try:
        response = requests.get(url, headers=headers)
        if response.status_code == 200:
            print("Success:", response.text)
        else:
            print("Failed to retrieve the webpage")
    except requests.exceptions.RequestException as e:
        print(f"An error occurred: {e}")
 
url = "https://www.huawei.com/en/interview-questions"  # 华为面试问题页面
get_huawei_interview_questions(url)

这段代码使用了Python的requests库来获取华为面试问题页面的内容。首先定义了一个get_huawei_interview_questions函数,它接受一个URL作为参数,并设置了合适的请求头。然后使用requests.get方法来发送HTTP GET请求,并处理可能发生的异常。如果页面成功获取,它会打印出响应的文本内容;如果发生错误,它会打印出错误信息。

2024-08-17

Selenium 4 自动获取驱动(如 ChromeDriver, GeckoDriver 等)的常见问题及解决方法如下:

  1. 驱动不兼容

    • 解释:新版本的 Selenium 4 可能不兼容旧版本的浏览器驱动。
    • 解决方法:确保 Selenium 版本与浏览器驱动版本相兼容。可以访问官方文档或对应驱动的 GitHub 页面查看兼容性信息。
  2. 驱动路径问题

    • 解释:Selenium 可能找不到驱动的正确路径。
    • 解决方法:确保在指定 WebDriver 时传递正确的驱动路径。
  3. 权限问题

    • 解释:在某些操作系统上,运行 Selenium 可能因为权限不足导致无法启动浏览器。
    • 解决方法:确保运行 Selenium 的用户有足够权限,或者以管理员身份运行。
  4. 环境变量问题

    • 解释:在某些操作系统中,系统的环境变量可能没有正确设置驱动的路径。
    • 解决方法:手动将驱动程序的路径添加到系统的环境变量中。
  5. 浏览器更新问题

    • 解释:如果浏览器版本过旧,可能无法正确工作。
    • 解决方法:确保浏览器是最新版本,或者下载与之兼容的驱动版本。
  6. 驱动下载问题

    • 解释:手动下载的驱动可能不完整或损坏。
    • 解决方法:使用 Selenium 提供的驱动管理功能自动下载和配置驱动。
  7. 其他错误

    • 解释:可能是其他原因导致的错误,例如网络问题、Selenium 配置错误等。
    • 解决方法:根据错误信息具体分析解决。

在编写爬虫时,请确保遵循相关法律法规,尊重网站的robots.txt规则,并使用合适的用户代理(User-Agent),避免对网站的服务造成影响。