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.")
相关推荐
yuanpan5 分钟前
C#如何正确的停止一个多线程Task?CancellationTokenSource 的用法。
开发语言·c#
程高兴7 分钟前
单相交直交变频电路设计——matlab仿真+4500字word报告
开发语言·matlab
奋斗者1号20 分钟前
《Crawl4AI 爬虫工具部署配置全攻略》
网络·爬虫
hyhrosewind31 分钟前
Python函数基础:说明文档(多行注释),函数嵌套调用,变量作用域(局部,全局,global关键字),综合案例
python·变量作用域·函数说明文档(多行注释)·函数嵌套调用·局部变量和全局变量·函数内修改全局变量·global关键字
我真的不会C1 小时前
QT中的事件及其属性
开发语言·qt
一点.点1 小时前
李沐动手深度学习(pycharm中运行笔记)——04.数据预处理
pytorch·笔记·python·深度学习·pycharm·动手深度学习
一点.点1 小时前
李沐动手深度学习(pycharm中运行笔记)——07.自动求导
pytorch·笔记·python·深度学习·pycharm·动手深度学习
2501_906314322 小时前
优化无头浏览器流量:使用Puppeteer进行高效数据抓取的成本降低策略
开发语言·数据结构·数据仓库
让我们一起加油好吗2 小时前
【C++】类和对象(上)
开发语言·c++·visualstudio·面向对象
大霸王龙2 小时前
Python对比两张CAD图并标记差异的解决方案
python·opencv·计算机视觉