Найти - Пользователи
Полная версия: Парсинг с помощью selenium
Начало » Python для новичков » Парсинг с помощью selenium
1
Scorp1978
Помогите спарсить страницу https://www.rosseti-sib.ru/otkluchenie-energii/
selenium установил, запустил но в коде странице того что мне надо нет. Как быть.
Может можно как то без selenium.
xam1816
Scorp1978
но в коде странице того что мне надо нет
что нужно получить?
Scorp1978
таблицу списка отключений
Scorp1978
может кто подсказать
xam1816
Scorp1978
таблицу списка отключений

данные приходят в таблицу из другой ссылки, в браузере огненный лис можно увидеть её в режиме просмотра сети, как это делается есть в интернете
Scorp1978
поставил firefox не смог понять, ведь данные на странице есть я их вижу а как забрать
ZerG
попробуй все же bs4

 import requests
from bs4 import BeautifulSoup
# Define the target URL
url = "https://www.rosseti-sib.ru/otkluchenie-energii/"
# Fetch the HTML content
try:
    response = requests.get(url)
    response.raise_for_status()  # Raise an error for non-200 status codes
except requests.exceptions.RequestException as e:
    print(f"Error fetching URL: {e}")
    exit()
# Parse the HTML content
soup = BeautifulSoup(response.content, 'html.parser')
# Extract relevant data using more specific selectors and logic
# (replace these with selectors based on the website's structure)
table_data = []
for row in soup.find_all('tr')[1:]:  # Skip the header row
    date_cell = row.find('td', class_='date')  # Assuming a class 'date'
    if date_cell:
        date = date_cell.text.strip()
    time_cell = row.find('td', class_='time')  # Assuming a class 'time'
    if time_cell:
        time = time_cell.text.strip()
    region_cell = row.find('td', class_='region')  # Assuming a class 'region'
    if region_cell:
        region = region_cell.text.strip()
    # Similarly, extract other data based on their selectors and logic
    table_data.append((date, time, region, ...))  # Add extracted data to list
# Print or use the table data as needed
print(table_data)
xam1816
  
import pandas as pd
import requests
import sqlite3
import tkinter as tk
from tkinter import ttk
data_url = 'https://www.rosseti-sib.ru/local/templates/rosseti/components/is/proxy/shutdown_schedule_table/data.php'
region_url = 'https://www.rosseti-sib.ru/local/templates/rosseti/components/is/proxy/shutdown_schedule_table/regions.php'
session = requests.session()
r = session.get(data_url)
if r.ok:
    data = r.json()
r = session.get(region_url)
if r.ok:
    regions = r.json()
data_table = pd.DataFrame(data)
reg_table = pd.DataFrame(regions)
conn = sqlite3.connect('energy_disable.db')
data_table.to_sql('data', conn, index=False, if_exists='replace')
reg_table.to_sql('regions', conn, index=False, if_exists='replace')
conn.close()
class FilterApp:
    def __init__(self, root):
        self.root = root
        self.root.title("SQLite Table Filter")
        self.conn = sqlite3.connect('energy_disable.db')
        self.cursor = self.conn.cursor()
        # Создаем и настраиваем виджеты интерфейса
        self.create_widgets()
    def create_widgets(self):
        self.filter_label = tk.Label(self.root, text="Filter by City:")
        self.filter_label.pack(pady=10)
        self.filter_entry = tk.Entry(self.root)
        self.filter_entry.pack(pady=10)
        self.filter_button = tk.Button(self.root, text="Apply Filter", command=self.apply_filter)
        self.filter_button.pack(pady=10)
        # Получаем заголовки из метаданных таблицы
        self.cursor.execute("PRAGMA table_info(data)")
        columns_info = self.cursor.fetchall()
        column_names = [info[1] for info in columns_info]
        print(column_names)
        self.tree = ttk.Treeview(self.root, show='headings', columns=column_names)
        self.v_scrollbar = ttk.Scrollbar(root, orient="vertical", command=self.tree.yview)
        self.v_scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
        self.tree.configure(yscrollcommand=self.v_scrollbar.set)
        # Создаем горизонтальный скроллбар и привязываем его к Treeview
        self.h_scrollbar = ttk.Scrollbar(root, orient="horizontal", command=self.tree.xview)
        self.h_scrollbar.pack(side=tk.BOTTOM, fill=tk.X)
        self.tree.configure(xscrollcommand=self.h_scrollbar.set)
        for col in column_names:
            self.tree.heading(col, text=col)
        self.tree.pack()
        self.apply_filter()
    def apply_filter(self):
        # Очищаем Treeview
        for item in self.tree.get_children():
            self.tree.delete(item)
        # Получаем значение из Entry
        filter_value = self.filter_entry.get()
        # Выполняем запрос с учетом фильтра
        query = f"SELECT * FROM data WHERE gorod LIKE '%{filter_value}%'"
        self.cursor.execute(query)
        # Получаем результаты запроса
        rows = self.cursor.fetchall()
        # Вставляем результаты в Treeview
        for row in rows:
            self.tree.insert('', 'end', values=row)
if __name__ == "__main__":
    root = tk.Tk()
    app = FilterApp(root)
    root.mainloop()
Rogal
Ну как, помогло?
Scorp1978
Всем неравнодушным спасибо!!! Буду пробовать, что получится отпишусь обязательно.
ZerG запустил Ваш код пусто. Вывел print(soup) там нет нужных данных по адресам.

xam1816, запустил код все работает как надо, но к сожалению понял что я вообще далек от знания python. Снимаю шляпу перед мастером. Всем еще раз спасибо. Пойду разбирать код.
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Powered by DjangoBB