2024-08-10



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://www.zhituce.com/')
 
# 等待页面加载textarea元素
textarea = WebDriverWait(driver, 10).until(
    EC.presence_of_element_located((By.ID, 'content'))
)
 
# 输入内容到textarea
textarea.send_keys('这里是测试内容')
 
# 删除textarea中的内容
textarea.clear()
 
# 输入修改后的内容
textarea.send_keys('这里是修改后的内容')
 
# 提交表单
submit_button = driver.find_element(By.ID, 'sub-btn')
submit_button.click()
 
# 等待页面处理完毕
time.sleep(2)
 
# 关闭浏览器
driver.quit()

这段代码使用了Selenium WebDriver来操作Chrome浏览器。首先,它打开智谱清言的官网,然后等待页面上的textarea元素加载完成,接着在textarea中输入内容,删除原有内容,再次输入修改后的内容,并最后点击提交按钮。最后关闭浏览器。这个过程模拟了一个用户的正常操作流程,对于学习爬虫技巧有很好的教育价值。

2024-08-10



library(htmltab)
 
# 定义一个函数来获取指定城市的天气信息
get_weather_info <- function(city) {
  # 构造目标网页的URL
  url <- sprintf("https://www.aqistudy.cn/historydata/daydata.php?city=%s", city)
  
  # 使用htmltab从网页中提取表格数据
  tryCatch({
    weather_table <- htmltab(url, trim = TRUE)
    
    # 处理表格数据,根据需要进行更多的数据清洗和转换
    if (nrow(weather_table) > 0) {
      # 将日期字符串转换为日期对象
      weather_table$日期 <- as.Date(weather_table$日期, format = "%Y-%m-%d")
      # 返回处理后的数据
      return(weather_table)
    } else {
      message("没有找到数据")
    }
  }, error = function(e) {
    message("网页解析错误: ", conditionMessage(e))
  })
}
 
# 示例:获取"北京"的天气信息
beijing_weather <- get_weather_info("北京")
print(beijing_weather)

这段代码定义了一个函数get_weather_info,它接受一个城市名称作为参数,构造相应的URL,使用htmltab函数从网页中提取表格数据,并对提取的数据进行简单的处理(例如日期格式转换)。然后,它尝试提取数据,并在出现错误时捕获异常,打印相关的错误信息。最后,它提供了一个使用这个函数获取特定城市天气信息的示例。

2024-08-10



import requests
from bs4 import BeautifulSoup
 
def get_html(url):
    """发送HTTP请求,获取网页内容"""
    try:
        response = requests.get(url)
        if response.status_code == 200:
            return response.text
        else:
            return "页面请求失败"
    except requests.RequestException:
        return "请求出错"
 
def parse_html(html):
    """解析网页,提取需要的信息"""
    soup = BeautifulSoup(html, 'html.parser')
    # 假设我们要提取所有的段落文本
    paragraphs = soup.find_all('p')
    for p in paragraphs:
        print(p.get_text())
 
def main():
    url = "https://example.com"  # 替换为你要爬取的网站
    html = get_html(url)
    parse_html(html)
 
if __name__ == "__main__":
    main()

这段代码展示了如何使用requests库发送HTTP请求,以及如何使用BeautifulSoup库解析HTML并提取所需信息。代码中的get_html函数负责发送请求,parse_html函数负责解析HTML,并打印段落文本。main函数则是程序的入口点,负责组织整个流程。在实际应用中,你需要根据目标网站的结构来调整解析代码,以提取你需要的数据。

2024-08-10



import requests
 
# 设置代理服务器
proxies = {
    'http': 'http://10.10.1.10:3128',
    'https': 'http://10.10.1.10:2080',
}
 
# 通过代理发送请求
response = requests.get('http://example.org', proxies=proxies)
 
# 打印响应内容
print(response.text)

这段代码展示了如何在使用requests模块发送HTTP请求时,通过proxies参数设置代理服务器,并发送一个GET请求到http://example.org。代理服务器的地址和端口分别对应HTTP和HTTPS协议。代码中还包含了如何打印响应内容的简单示例。

2024-08-10



import requests
 
# 目标网页URL
url = 'https://example.com/some_text'
 
# 发送HTTP GET请求
response = requests.get(url)
 
# 检查请求是否成功
if response.status_code == 200:
    # 解析响应内容,这里假设网页内容是纯文本
    text = response.text
    
    # 打印或处理文本内容
    print(text)
    
    # 保存到文件(如果需要)
    with open('downloaded_text.txt', 'w', encoding='utf-8') as file:
        file.write(text)
else:
    print(f"请求失败,状态码: {response.status_code}")

这段代码使用了requests库来发送一个HTTP GET请求到指定的URL,获取网页内容,并打印出来。如果你需要将内容保存到文件,可以取消注释保存到文件的部分代码。这是一个简单的Python爬虫示例,适合作为学习如何开始编写爬虫的起点。

2024-08-10



import requests
from bs4 import BeautifulSoup
import re
import pandas as pd
 
# 示例函数:从指定的新闻网站爬取新闻标题和链接
def crawl_news(url):
    response = requests.get(url)
    soup = BeautifulSoup(response.text, 'html.parser')
    news_items = soup.find_all('div', class_='news-item')
    news_data = []
    for item in news_items:
        title = item.find('a').text
        link = item.find('a')['href']
        news_data.append({'title': title, 'link': link})
    return news_data
 
# 示例函数:使用正则表达式提取新闻内容中的关键词
def extract_keywords(content):
    keywords = re.findall(r'[a-zA-Z]+', content)
    return keywords
 
# 示例函数:将新闻数据转化为DataFrame格式
def prepare_dataframe(news_data):
    df = pd.DataFrame(news_data)
    return df
 
# 示例函数:使用K-means算法对新闻进行聚类
from sklearn.cluster import KMeans
 
def cluster_news(data, k=5):
    kmeans = KMeans(n_clusters=k)
    kmeans.fit(data)
    return kmeans.labels_
 
# 示例函数:根据用户的兴趣喜好,推荐相关新闻
def recommend_news(user_interests, news_data):
    recommended_news = [news for news in news_data if any(interest in news.keywords for interest in user_interests)]
    return recommended_news
 
# 示例函数:将新闻推荐给用户
def present_recommendation(recommended_news):
    for news in recommended_news:
        print(f"新闻标题: {news.title}")
        print(f"新闻链接: {news.link}\n")
 
# 假设的用户兴趣喜好
user_interests = ['科技', '健康']
 
# 假设的新闻网站URL
news_url = 'https://example.com/news'
 
# 爬取新闻
news_items = crawl_news(news_url)
 
# 为新闻数据准备DataFrame
df = prepare_dataframe(news_items)
 
# 为新闻数据提取关键词
df['keywords'] = df['title'].apply(extract_keywords)
 
# 使用K-means算法对新闻进行聚类
cluster_labels = cluster_news(df[['title', 'link']])
df['cluster'] = cluster_labels
 
# 根据用户的兴趣喜好,推荐相关新闻
recommended_news = recommend_news(user_interests, df)
 
# 将新闻推荐给用户
present_recommendation(recommended_news)

这个代码示例展示了如何使用Python爬取新闻网站的新闻标题和链接,如何提取关键词,如何使用K-means算法对新闻进行聚类,以及如何根据用户的兴趣喜好推荐相关新闻。这个过程是一个简化的示例,实际应用中需要更复杂的数据预处理和算法优化。

2024-08-10



import numpy as np
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
 
# 示例用户和新闻数据
users = {
    'Alice': ['news_1', 'news_3'],
    'Bob': ['news_1', 'news_4'],
    'Eve': ['news_2', 'news_3'],
    # ... 更多用户数据
}
news_database = {
    'news_1': 'Bitcoin price soars to new heights.',
    'news_2': 'Elon Musk talks about SpaceX.',
    'news_3': 'Tesla sales surge, stock price soars.',
    'news_4': 'Amazon goes public.',
    # ... 更多新闻数据
}
 
# 创建新闻-用户协同过滤推荐系统
def news_recommender(user):
    # 获取用户喜欢的新闻列表
    user_news_list = users[user]
    
    # 创建新闻-用户矩阵
    M = np.zeros((len(news_database), len(users)))
    for i, news_id in enumerate(news_database):
        for j, user_id in enumerate(users):
            if news_id in users[user_id]:
                M[i, j] = 1
    
    # 计算用户相似度矩阵
    sim_matrix = 1 - cosine_similarity(M)
    
    # 为当前用户生成新闻推荐
    recommendations = []
    for i, sim in enumerate(sim_matrix[i]):
        if sim > 0 and i not in user_news_list:
            recommendations.append((sim, list(news_database.keys())[i]))
    
    # 根据相似度从高到低排序,并返回推荐新闻
    return sorted(recommendations, reverse=True)
 
# 示例:为用户'Alice'生成新闻推荐
print(news_recommender('Alice'))

这段代码首先定义了一些示例用户和新闻数据,然后创建了一个新闻-用户协同过滤推荐系统的函数news_recommender。该函数首先构建了一个新闻-用户矩阵M,然后计算用户相似度矩阵sim_matrix,接着基于相似度为指定用户生成新闻推荐,并返回排序后的推荐列表。最后,我们为用户'Alice'生成了新闻推荐并打印输出。

2024-08-10

为了创建一个基于DrissionPage库的词云图,你需要先安装该库,并使用它来抓取指定页面的文本内容。然后,你可以使用jieba库进行中文分词,最后使用wordcloud库生成词云图。以下是一个简单的示例代码:




import asyncio
from drission_page import DrissionPage
from drission_page.utils.common_funcs import get_random_char_and_num
from PIL import Image
import numpy as np
from wordcloud import WordCloud
import jieba
import matplotlib.pyplot as plt
 
# 初始化DrissionPage
async def main():
    dp = DrissionPage()
    await dp.init_chromium()
 
    # 目标网页URL
    url = 'http://example.com'
 
    # 获取网页文本内容
    text = await dp.get_page_text(url)
 
    # 使用jieba进行中文分词
    wordlist = jieba.cut(text)
    text = ' '.join(wordlist)
 
    # 创建词云图
    font = r'C:\Windows\Fonts\simfang.ttf'  # 指定中文字体路径
    color_mask = np.array(Image.open(r'C:\path\to\your\mask\image.png'))  # 可以使用自定义图片作为遮罩
    wordcloud = WordCloud(font_path=font, background_color="white", mask=color_mask, max_words=2000, max_font_size=100, random_state=42)
    wordcloud.generate(text)
 
    # 展示词云图
    plt.imshow(wordcloud, interpolation='bilinear')
    plt.axis('off')
    plt.show()
 
    # 关闭浏览器
    await dp.quit()
 
# 运行异步主函数
asyncio.run(main())

确保替换http://example.com为你想要抓取的网页URL,并指定正确的中文字体路径和遮罩图片路径。

注意:以上代码示例仅用于演示如何使用DrissionPage和相关库生成词云图,并不包含错误处理和异常情况处理。在实际应用中,你需要添加更多的异常处理逻辑以确保代码的稳定性和容错性。

2024-08-10

由于Instagram不推荐使用API进行数据爬取,可能会违反服务条款,这里提供一个简单的示例来说明如何使用Python爬取Instagram的图片。




import requests
import os
 
# 设置Instagram的用户名
username = 'instagram'
 
# 设置保存图片的路径
save_path = 'instagram_images'
 
# 确保保存路径存在
if not os.path.exists(save_path):
    os.makedirs(save_path)
 
# 设置图片的URL前缀
url_prefix = f'https://www.instagram.com/{username}/'
 
# 发送HTTP GET请求
response = requests.get(url_prefix)
 
# 确保请求成功
if response.status_code == 200:
    # 解析响应内容,寻找图片链接
    # 这里需要使用Instagram的API或者正则表达式等来提取图片链接
    # 示例中省略了具体实现
    # image_urls = parse_response(response.text)
    image_urls = []  # 假设我们已经找到了所有图片的URL
 
    # 下载并保存图片
    for i, image_url in enumerate(image_urls):
        response = requests.get(image_url)
        if response.status_code == 200:
            file_path = os.path.join(save_path, f'{i}.jpg')
            with open(file_path, 'wb') as file:
                file.write(response.content)
            print(f'Image {i} saved successfully.')
        else:
            print(f'Failed to download image {i}.')
else:
    print('Failed to retrieve Instagram page.')

请注意,这个代码示例省略了解析响应内容以找到图片链接的部分,实际应用中你需要使用合适的方法来提取这些信息。此外,由于Instagram的页面结构可能会改变,所以解析逻辑也需要定期更新。

此代码只是一个简单的示例,并不适合用于大规模数据爬取,且在没有遵守Instagram的使用条款的情况下使用其API是非法的,应当确保你有权限和明确的许可来进行这样的操作。

2024-08-10

在Python中,可以使用requests库获取网页内容,再使用BeautifulSoup库解析网页,提取出我们需要的数据。以下是一个简单的例子,用于获取申万一级行业数据:




import requests
from bs4 import BeautifulSoup
 
def get_swjy_data():
    # 申万一级行业数据的网址
    url = 'http://www.sinomoney.com.cn/data/swjy/'
    # 发送HTTP请求
    response = requests.get(url)
    # 检查请求是否成功
    if response.status_code == 200:
        # 使用BeautifulSoup解析网页内容
        soup = BeautifulSoup(response.text, 'html.parser')
        # 找到包含数据的表格
        table = soup.find('table', {'class': 'tablelist'})
        # 提取表格中的数据
        data_rows = table.find_all('tr')[1:]  # 跳过表头
        data = []
        for row in data_rows:
            # 提取每一行的数据
            cols = row.find_all('td')
            # 确保数据格式正确
            if len(cols) == 7:
                data.append({
                    'rank': cols[0].text.strip(),
                    'industry': cols[1].text.strip(),
                    'swjy': cols[2].text.strip(),
                    'value': cols[3].text.strip(),
                    'increase': cols[4].text.strip(),
                    'market_cap': cols[5].text.strip(),
                    'industry_cap': cols[6].text.strip()
                })
        return data
    else:
        print("Failed to retrieve data, status code:", response.status_code)
        return None
 
# 使用函数获取数据
swjy_data = get_swjy_data()
# 打印获取到的数据
if swjy_data:
    for entry in swjy_data:
        print(entry)

请注意,网站可能会更改其结构,这可能会影响解析代码的有效性。此外,自动抓取数据可能违反网站的服务条款,应确保您的行为符合网站规定,并尊重网站的数据使用政策。