python爬取网页源代码,提取关键词信息

python 复制代码
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
import time
import csv
from tqdm import tqdm

# 设置Chrome选项,使其在无头模式下运行
chrome_options = Options()
chrome_options.add_argument('--headless')
chrome_options.add_argument('--disable-gpu')
chrome_options.add_argument('--no-sandbox')
# 禁止加载图片
prefs = {"profile.managed_default_content_settings.images": 2}
chrome_options.add_experimental_option("prefs", prefs)

# CSV文件名
csv_file = 'lists_3.csv'
# 指定ChromeDriver的路径
driver_path = '/usr/bin/chromedriver'

# 创建一个Service对象
service = Service(driver_path)

# 创建WebDriver实例
driver = webdriver.Chrome(service=service, options=chrome_options)

# 从CSV文件读取URL列表
urls = []
with open(csv_file, mode='r', encoding='utf-8') as file:
    csv_reader = csv.reader(file)
    for row in csv_reader:
        if row:  # 确保行不是空的
            urls.append(row[0])  # 假设URL在每行的第一个元素

# 输出文件
output_file = 'code.txt'

# 使用'a'模式打开输出文件
with open(output_file, 'a', encoding='utf-8') as file:
    for url in tqdm(urls, desc="Processing URLs"):
        try:
            # 访问URL
            driver.get(url)
            
            # 显式等待页面标题出现
            WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.TAG_NAME, "title")))
            
            # 获取页面标题
            title = driver.title
            
            # 尝试获取<title>,并写入文件
            file.write(f"{url}\n")
            file.write(f"Title: {title}\n")
            
            # 尝试获取<meta name="keywords">
            try:
                WebDriverWait(driver, 5).until(EC.presence_of_element_located((By.NAME, "keywords")))
                keywords = driver.find_element(By.NAME, 'keywords').get_attribute('content')
                file.write(f"Keywords: {keywords}\n")
            except Exception:
                file.write("Keywords: Not Found\n")
            
            # 尝试获取<meta name="description">
            try:
                WebDriverWait(driver, 5).until(EC.presence_of_element_located((By.NAME, "description")))
                description = driver.find_element(By.NAME, 'description').get_attribute('content')
                file.write(f"Description: {description}\n")
            except Exception:
                file.write("Description: Not Found\n")
            
            file.write("\n")  # 分隔不同URL的元数据
            file.flush()  # 强制刷新文件缓冲
            
        except Exception as e:
            print(f"An error occurred while processing {url}: {str(e)}")
            continue  # 跳过错误URL,继续处理下一个

# 关闭WebDriver实例
driver.quit()

print("All data has been written to the output file.")
相关推荐
安之若素^3 分钟前
启用不安全的HTTP方法
java·开发语言
周树皮不皮8 分钟前
20250704【翻转&二叉树】|Leetcodehot100之226【pass】&今天计划
python
魔芋红茶9 分钟前
spring-initializer
python·学习·spring
喜欢吃豆13 分钟前
快速手搓一个MCP服务指南(九): FastMCP 服务器组合技术:构建模块化AI应用的终极方案
服务器·人工智能·python·深度学习·大模型·github·fastmcp
一个天蝎座 白勺 程序猿20 分钟前
Python(28)Python循环语句指南:从语法糖到CPython字节码的底层探秘
开发语言·python
持梦远方1 小时前
C 语言基础入门:基本数据类型与运算符详解
c语言·开发语言·c++
zzywxc7871 小时前
AI 正在深度重构软件开发的底层逻辑和全生命周期,从技术演进、流程重构和未来趋势三个维度进行系统性分析
java·大数据·开发语言·人工智能·spring
weixin_416639971 小时前
爬虫工程师Chrome开发者工具简单介绍
前端·chrome·爬虫
3gying1 小时前
chromedriver
python
灵性花火1 小时前
Qt的前端和后端过于耦合(0/7)
开发语言·前端·qt