Nguyễn Nam

Internal linking (liên kết nội bộ) là một phần quan trọng trong chiến lược SEO, giúp cải thiện cấu trúc trang web và trải nghiệm người dùng. Việc trực quan hóa các liên kết nội bộ sẽ giúp bạn dễ dàng đánh giá cách các trang liên kết với nhau, từ đó tối ưu hóa cấu trúc trang web.

Bài viết này hướng dẫn bạn cách sử dụng Python để tạo sơ đồ liên kết nội bộ bằng NetworkX và Pyvis. Quá trình này sẽ giúp bạn thu thập, phân tích và trực quan hóa các liên kết nội bộ trên website.


1. Cài Đặt Môi Trường

Trước khi bắt đầu, bạn cần cài đặt các thư viện cần thiết:

!pip install pyvis networkx pandas

Các thư viện chính được sử dụng:


2. Nạp Dữ Liệu Liên Kết Nội Bộ

Dữ liệu liên kết nội bộ được lấy từ tệp CSV chứa danh sách các trang và các liên kết bên trong nội dung. Bạn có thể tải tệp này lên Google Colab hoặc máy tính của mình.

import pandas as pd
import re
import networkx as nx
from pyvis.network import Network
from google.colab import drive

# Kết nối Google Drive (nếu chạy trên Colab)
drive.mount('/content/drive')

# Đọc dữ liệu từ tệp CSV
file_path = '/content/custom_extraction_related.csv'  # Cập nhật đường dẫn tệp

data = pd.read_csv(file_path, on_bad_lines='skip')

3. Xử Lý Và Làm Sạch Dữ Liệu

Chúng ta cần làm sạch dữ liệu để chỉ giữ lại các đường dẫn có liên quan.

def clean_and_extract_links(data):
    data['related 3'] = data['related 3'].astype(str)
    data['Address'] = data['Address'].str.replace('https://magiclinen.com/', '', regex=False)

    # Trích xuất liên kết từ thẻ <a>
    data['extracted_links'] = data['related 3'].apply(lambda x: re.findall(r'<a href="(?![#])(?!https?://)([^"]+)">([^<]+)</a>', x))

    # Lọc các dòng có liên kết nội bộ
    extracted_data = data[data['extracted_links'].str.len() > 0]

    # Chuyển danh sách liên kết thành các cột riêng biệt
    expanded_links = extracted_data.explode('extracted_links')
    expanded_links[['Path', 'Phrase']] = pd.DataFrame(expanded_links['extracted_links'].tolist(), index=expanded_links.index)

    # Xóa domain khỏi đường dẫn
    expanded_links['Path'] = expanded_links['Path'].str.replace('https://magiclinen.com/', '', regex=False)

    # Lưu dữ liệu đã làm sạch vào tệp CSV
    output_file_path = '/content/cleaned_extracted_data.csv'
    expanded_links[['Address', 'Status Code', 'Status', 'Path', 'Phrase']].to_csv(output_file_path, index=False)
    print(f"CSV file saved to {output_file_path}")

    return expanded_links[['Address', 'Status Code', 'Status', 'Path', 'Phrase']]

cleaned_extracted_data = clean_and_extract_links(data)

4. Xây Dựng Đồ Thị Liên Kết Nội Bộ

Dữ liệu liên kết nội bộ sẽ được chuyển thành một đồ thị có hướng (directed graph) sử dụng NetworkX.

G = nx.DiGraph()
for address, group in cleaned_extracted_data.groupby('Address'):
    for _, row in group.iterrows():
        G.add_edge(address, row['Path'], phrase=row['Phrase'])

5. Trực Quan Hóa Internal Links Bằng Pyvis

Sử dụng Pyvis để tạo sơ đồ liên kết với giao diện tương tác.

net = Network(notebook=True, height="750px", width="100%", bgcolor="#222222", font_color="white", cdn_resources='in_line')

# Thêm các node và edges vào biểu đồ
for node in G.nodes():
    net.add_node(node, label=node, color="lightgray" if node in cleaned_extracted_data['Address'].values else "lightblue", size=10)

for source, target, edge_data in G.edges(data=True):
    label = edge_data.get('phrase', '')
    net.add_edge(source, target, title=label, color="gray", arrows="to")

# Cấu hình giao diện trực quan
net.set_options("""
{
  "nodes": {
    "borderWidth": 1,
    "color": { "highlight": { "background": "lightgreen", "border": "lightgreen" } },
    "font": { "size": 14, "color": "white", "face": "Arial" }
  },
  "edges": {
    "width": 1,
    "arrows": { "to": { "enabled": true, "scaleFactor": 0.5 } },
    "color": { "color": "gray", "highlight": "lightgreen", "hover": "lightgreen" },
    "smooth": { "enabled": false }
  },
  "interaction": { "hover": true, "hoverConnectedEdges": true, "selectConnectedEdges": true, "tooltipDelay": 200 },
  "physics": { "enabled": true, "barnesHut": { "gravitationalConstant": -2000, "centralGravity": 0.2, "springLength": 600, "springConstant": 0.05 } }
}
""")

# Xuất đồ thị dưới dạng file HTML
net.show("internal_link_graph.html")

6. Ứng Dụng Trong SEO


Kết Luận

Với Python, bạn có thể tự động thu thập và trực quan hóa sơ đồ liên kết nội bộ của một website. Công cụ này giúp bạn dễ dàng tối ưu cấu trúc liên kết để cải thiện SEO và trải nghiệm người dùng.

13 Responses

Leave a Reply

Your email address will not be published. Required fields are marked *

Solverwp- WordPress Theme and Plugin