2024-08-16



import requests
from bs4 import BeautifulSoup
import pandas as pd
import matplotlib.pyplot as plt
 
# 获取房源数据
def get_data(url):
    response = requests.get(url)
    soup = BeautifulSoup(response.text, 'html.parser')
    data = soup.find_all('div', class_='info-panel')
    houses = []
    for item in data:
        house = {
            'title': item.find('div', class_='title').text,
            'price': item.find('div', class_='price').text,
            'area': item.find('div', class_='area').text,
            'link': item.find('a')['href']
        }
        houses.append(house)
    return houses
 
# 分析并可视化数据
def analyze_visualize(houses):
    df = pd.DataFrame(houses)
    # 只保留有价格信息的房源
    df = df[df['price'].notna()]
    # 提取单价并转换为浮点数
    df['unit_price'] = df['price'].str.extract(r'(\d+)\s*元/平').astype('float')
    # 计算总价并转换为浮点数
    df['total_price'] = df['link'].str.extract(r'&(?:totalPrice|money)=(\d+)').astype('float')
    # 绘制单价直方图
    plt.hist(df['unit_price'], bins=50)
    plt.xlabel('Unit Price (元/平米)')
    plt.ylabel('House Counts')
    plt.title('Histogram of Unit Price')
    plt.show()
 
# 主函数
def main():
    url = 'http://hz.lianjia.com/ershoufang/anhuigongyu/'
    houses = get_data(url)
    analyze_visualize(houses)
 
if __name__ == '__main__':
    main()

这段代码实现了一个简单的房源数据爬取、分析和可视化的过程。首先,我们定义了一个get_data函数来获取安徽合肥二手房源的数据。接着,在analyze_visualize函数中,我们使用Pandas来处理数据,并使用matplotlib绘制单价直方图,最后在main函数中调用这两个函数来执行整个流程。这个例子展示了如何使用Python进行网页数据爬取和数据分析,是学习网络爬虫和数据可视化的一个很好的起点。

2024-08-16

该项目是一个使用SpringBoot框架开发的校园BA篮球网站,包含了前后端的代码。前端主要使用了HTML/CSS/JavaScript以及Vue.js进行开发,后端主要使用了SpringBoot框架以及MyBatis进行开发。

以下是一个简单的代码示例,展示了如何在SpringBoot中创建一个控制器:




package com.example.controller;
 
import com.example.entity.User;
import com.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
 
@RestController
@RequestMapping("/api/user")
public class UserController {
 
    @Autowired
    private UserService userService;
 
    @PostMapping("/register")
    public User register(@RequestBody User user) {
        return userService.register(user);
    }
 
    @GetMapping("/{userId}")
    public User getUserById(@PathVariable("userId") Long userId) {
        return userService.getUserById(userId);
    }
 
    @PutMapping("/{userId}")
    public User updateUser(@PathVariable("userId") Long userId, @RequestBody User user) {
        return userService.updateUser(userId, user);
    }
 
    @DeleteMapping("/{userId}")
    public void deleteUser(@PathVariable("userId") Long userId) {
        userService.deleteUser(userId);
    }
}

在这个示例中,我们定义了一个UserController,它提供了用户的注册、获取、更新和删除的接口。这些接口通过HTTP请求进行交互,并且使用了Spring的注解来简化开发流程。

请注意,该代码仅为示例,实际项目中可能需要更多的功能和逻辑。获取整个项目的源代码和数据库可以通过提供的链接进行。

2024-08-16



import requests
from bs4 import BeautifulSoup
 
# 爬取网页的函数
def crawl_page(url):
    try:
        response = requests.get(url)
        if response.status_code == 200:
            return response.text
        else:
            return None
    except requests.RequestException:
        return None
 
# 解析网页并提取信息的函数
def parse_soup(soup):
    # 假设我们要提取的信息是标题
    title = soup.find('title')
    return title.text if title else None
 
# 主函数,组织爬取和解析的流程
def main():
    url = 'https://www.example.com'  # 替换为你要爬取的网址
    html = crawl_page(url)
    if html:
        soup = BeautifulSoup(html, 'html.parser')
        parsed_info = parse_soup(soup)
        if parsed_info:
            print(f"The title of the page is: {parsed_info}")
        else:
            print("No useful data was found.")
    else:
        print("Failed to retrieve the webpage.")
 
if __name__ == "__main__":
    main()

这段代码展示了如何使用Python的requests库来爬取网页,以及如何使用BeautifulSoup来解析网页并提取信息。代码中的crawl_page函数负责发送HTTP请求,获取网页内容,而parse_soup函数负责解析HTML并提取需要的数据。最后,main函数组合了这两个功能,并且还增加了错误处理和打印输出。

2024-08-16

urlliburllib3都是Python中用于处理URL的模块,但它们有一些区别。

urllib是Python自带的库,包含了几个用于操作URL的模块。urllib.request用于打开和读取URLs,urllib.parse用于解析URLs,urllib.error包含了由于网络操作产生的异常。

urllib3是一个专门用于HTTP客户端的模块,它提供了更高级的功能,比如并发请求、会话处理等。

以下是使用urllib.request获取网页内容的简单例子:




import urllib.request
 
# 打开一个URL
response = urllib.request.urlopen('http://www.example.com')
 
# 读取网页内容
html = response.read()
 
# 解码网页内容(如果网页使用UTF-8编码)
html_decoded = html.decode('utf-8')
 
print(html_decoded)

使用urllib3的例子:




import urllib3
 
# 创建一个PoolManager实例
http = urllib3.PoolManager()
 
# 发送一个GET请求
response = http.request('GET', 'http://www.example.com')
 
# 读取响应内容
html = response.data
 
# 解码内容
html_decoded = html.decode('utf-8')
 
print(html_decoded)

在实际应用中,如果只是需要进行简单的HTTP请求,推荐使用urllib.request。如果需要更高级的功能,比如并发请求、请求重试等,则推荐使用urllib3

2024-08-16



import requests
from bs4 import BeautifulSoup
import re
 
def get_bilibili_top100(top100_url):
    # 发送请求,获取页面源代码
    response = requests.get(top100_url)
    response.raise_for_status()
    soup = BeautifulSoup(response.text, 'lxml')
 
    # 提取视频封面图片的正则表达式
    cover_regex = re.compile(r'//.*?cover')
 
    # 提取视频源代码的正则表达式
    video_source_regex = re.compile(r'<source src="(.*?)".*?>')
 
    # 遍历页面,查找视频封面图片和视频源
    covers = cover_regex.findall(response.text)
    video_sources = video_source_regex.findall(response.text)
 
    # 输出结果
    for cover, video_source in zip(covers, video_sources):
        print(f"封面图片: {cover}")
        print(f"视频源: {video_source}")
 
# 使用函数
get_bilibili_top100('https://www.bilibili.com/v/popular/rank/type?tab=all')

这段代码使用了requests库来发送HTTP请求,获取B站TOP100视频页面的HTML内容。然后使用BeautifulSoup和正则表达式来提取视频封面图片的URL和视频源的URL。最后,遍历页面中的视频信息,并打印出封面图片和视频源的URL。

2024-08-16

要爬取淘宝的商品数据,你可以使用Python的requests和lxml库来实现。以下是一个简单的例子,展示如何获取淘宝商品页面的某些信息:




import requests
from lxml import etree
 
def get_item_info(item_url):
    headers = {
        'User-Agent': 'your_user_agent',  # 替换为你的User-Agent
    }
    response = requests.get(item_url, headers=headers)
    if response.status_code == 200:
        html = response.text
        tree = etree.HTML(html)
        
        # 获取商品标题
        title = tree.xpath('//div[@class="tb-detail-hd"]/h1/text()')[0]
        print(f'商品标题: {title}')
        
        # 获取商品价格
        price = tree.xpath('//div[@class="price"]/strong/text()')[0]
        print(f'商品价格: {price}')
        
        # 获取商品评分
        score = tree.xpath('//div[@class="rate-content"]/@title')[0]
        print(f'商品评分: {score}')
        
        # 获取商品销售量
        sales = tree.xpath('//div[@class="deal-cnt"]/text()')[0]
        print(f'商品销售量: {sales}')
    else:
        print('获取页面失败')
 
item_url = 'https://item.taobao.com/item.htm?id=商品ID'  # 替换为具体的商品ID
get_item_info(item_url)

请注意,你需要替换your_user_agent为你自己的User-Agent,以及将商品ID替换为具体的淘宝商品编号。此外,由于淘宝采取了反爬措施,如果频繁访问,可能需要使用代理和合适的请求头信息,以避免被淘宝服务器封禁。

此代码只是一个简单的示例,实际爬取时你可能需要处理更多的数据和面对更复杂的情况,例如动态加载的数据、登录验证等。

2024-08-16



import requests
import pandas as pd
from pyecharts.charts import Bar, Line
from pyecharts import options as opts
 
# 获取数据
def get_data(url):
    response = requests.get(url)
    return response.json()
 
# 解析数据
def parse_data(data):
    records = data['records']
    provinces = [record['provinceName'] for record in records]
    confirmed_cases = [record['confirmedCount'] for record in records]
    suspected_cases = [record['suspectedCount'] for record in records]
    cured_cases = [record['curedCount'] for record in records]
    dead_cases = [record['deadCount'] for record in records]
    return provinces, confirmed_cases, suspected_cases, cured_cases, dead_cases
 
# 可视化数据
def visualize_data(provinces, confirmed_cases, suspected_cases, cured_cases, dead_cases):
    # 确诊变异情况柱状图
    bar = Bar()
    bar.add_xaxis(provinces)
    bar.add_yaxis("确诊", confirmed_cases)
    bar.add_yaxis("疑似", suspected_cases)
    bar.set_global_opts(title_opts=opts.TitleOpts(title="变异情况柱状图"))
    bar.render("变异情况.html")
 
    # 累计治愈和死亡情况折线图
    line = Line()
    line.add_xaxis(provinces)
    line.add_yaxis("治愈", cured_cases, is_smooth=True)
    line.add_yaxis("死亡", dead_cases, is_smooth=True)
    line.set_global_opts(title_opts=opts.TitleOpts(title="治愈与死亡累计折线图"))
    line.render("治愈与死亡.html")
 
# 主函数
def main():
    url = "https://api.inews.qq.com/newsqa/v1/automation/modules/list?modules=FAutoCountry,WomWorld,AiCountry,WomAboard,CountryOther,OverseaFightForecast,WomAboardForecast,GlobalFight,ChinaFight,FightAroundWorld,FightCountry,FightProvince,FightType,MasksSupplies,FightForecast,FightTips,FightAroundWorldForecast,CountryOtherForecast&_=1615366747766"
    data = get_data(url)
    provinces, confirmed_cases, suspected_cases, cured_cases, dead_cases = parse_data(data)
    visualize_data(provinces, confirmed_cases, suspected_cases, cured_cases, dead_cases)
 
if __name__ == "__main__":
    main()

这段代码使用了pyecharts库来创建图表,并且使用requests库来发送HTTP请求从网络上获取数据。首先定义了一个获取数据的函数,然后解析数据,并定义了一个可视化数据的函数。最后,在主函数中调用这些函数来完成数据的爬取和可视化展示。

2024-08-16



import requests
from bs4 import BeautifulSoup
import re
import time
 
def get_soup(url):
    """
    获取网页内容并返回BeautifulSoup对象
    """
    headers = {
        'User-Agent': 'Mozilla/5.0',
        'From': 'your_email@example.com' # 替换为你的邮箱
    }
    try:
        response = requests.get(url, headers=headers)
        if response.status_code == 200:
            return BeautifulSoup(response.text, 'html.parser')
    except requests.RequestException:
        print(f"An error occurred while trying to retrieve {url}")
        time.sleep(5)
 
def extract_links(soup):
    """
    从BeautifulSoup对象中提取新闻链接
    """
    # 根据实际HTML结构修改选择器
    return [link['href'] for link in soup.select('a.news-title') if link.get('href') and re.match(r'^http', link['href'])]
 
def main():
    url = 'http://example.com/news' # 替换为你要爬取的新闻网站
    soup = get_soup(url)
    if soup:
        links = extract_links(soup)
        for link in links:
            print(link)
 
if __name__ == '__main__':
    main()

这段代码提供了一个简单的网络爬虫示例,用于从一个假设的新闻网站中提取新闻链接。在实际应用中,你需要替换'example.com/news'为你要爬取的实际网站,并确保选择器(如'a.news-title')匹配目标网站的HTML结构。此外,记得遵守网站的robots.txt规则和法律法规,尊重网站版权和隐私政策。

2024-08-16



# 导入Django模型
from django.db import models
 
# 定义爬虫项目模型
class Project(models.Model):
    name = models.CharField(max_length=200)
    # 其他字段...
 
# 定义爬虫任务模型
class Task(models.Model):
    project = models.ForeignKey(Project, on_delete=models.CASCADE)
    url = models.URLField()
    # 其他字段...
 
# 定义爬虫统计模型
class Statistic(models.Model):
    task = models.ForeignKey(Task, on_delete=models.CASCADE)
    items_scraped = models.IntegerField()
    # 其他字段...

这个例子展示了如何使用Django的模型来定义一个简单的爬虫管理系统的数据结构。每个爬虫项目可以有多个爬虫任务,每个爬虫任务生成相应的统计数据。这个系统可以用来跟踪和管理企业级的爬虫项目。

2024-08-16



from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
 
# 初始化webdriver
driver = webdriver.Chrome()
 
# 打开网页
driver.get("http://example.com")
 
# 等待网页加载完成
wait = WebDriverWait(driver, 10)
wait.until(EC.presence_of_element_located((By.ID, "myElementId")))
 
# 执行动作链,模拟鼠标点击操作
actions = webdriver.ActionChains(driver)
actions.move_to_element(driver.find_element(By.ID, "myMenu")).click(driver.find_element(By.ID, "subMenu")).perform()
 
# 输入搜索内容
input_element = driver.find_element(By.ID, "mySearchBar")
input_element.send_keys("search keyword")
 
# 提交搜索
input_element.send_keys(Keys.RETURN)
 
# 滚动页面
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
 
# 等待动态内容加载
time.sleep(5)
 
# 获取页面源代码
page_source = driver.page_source
 
# 清理:关闭浏览器
driver.quit()

这段代码展示了如何使用Selenium WebDriver在Python中打开一个网页,执行鼠标点击、输入搜索关键字、提交搜索和滚动页面的基本操作。同时,它还展示了如何使用ActionChains来模拟复杂的用户动作。最后,代码中使用了time.sleep()来等待动态内容加载,这通常不是推荐的做法,可以使用WebDriverWait来代替,但出于教学目的,这里简化了处理方式。