顯示具有 網路爬蟲 標籤的文章。 顯示所有文章
顯示具有 網路爬蟲 標籤的文章。 顯示所有文章

2024年12月14日 星期六

用Python爬取網站內容:SEO 分析與評分

以下程式是由ChatGPT所產生。

安裝套件:

pip install requests beautifulsoup4


範例一、網站標題和描述

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
import requests
from bs4 import BeautifulSoup

def seo_scraper(url):
    response = requests.get(url)
    soup = BeautifulSoup(response.text, 'html.parser')

    title = soup.title.string if soup.title else 'No Title'
    meta_description = soup.find('meta', attrs={'name': 'description'})
    description = meta_description['content'] if meta_description else 'No Description'

    print(f"網站標題: {title}")
    print(f"網站描述: {description}")

# 測試範例
seo_scraper('https://example.com')

範例二、提取 SEO 相關資訊,如標題、描述、H1 標籤及所有內部連結

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import requests
from bs4 import BeautifulSoup
from urllib.parse import urljoin

def seo_analyze(url):
    try:
        # 發送 GET 請求
        response = requests.get(url)
        response.raise_for_status()  # 確保請求成功

        # 使用 BeautifulSoup 解析 HTML
        soup = BeautifulSoup(response.text, 'html.parser')

        # 提取標題
        title = soup.title.string if soup.title else 'No Title'
        print(f"網站標題: {title}")

        # 提取 meta 描述
        meta_description = soup.find('meta', attrs={'name': 'description'})
        description = meta_description['content'] if meta_description else 'No Description'
        print(f"網站描述: {description}")

        # 提取 H1 標籤
        h1_tags = soup.find_all('h1')
        h1_texts = [h1.get_text(strip=True) for h1 in h1_tags]
        print(f"H1 標籤: {h1_texts if h1_texts else 'No H1 Tags'}")

        # 提取內部連結
        internal_links = set()
        for a_tag in soup.find_all('a', href=True):
            href = a_tag['href']
            full_url = urljoin(url, href)
            if url in full_url:
                internal_links.add(full_url)

        print("\n內部連結:")
        for link in internal_links:
            print(link)

    except requests.RequestException as e:
        print(f"請求失敗: {e}")

# 測試範例
website_url = 'https://example.com'  # 替換為你要分析的網址
seo_analyze(website_url)

範例三、檢查圖片的 Alt 屬性,確保圖片有適當的描述
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import requests
from bs4 import BeautifulSoup
from urllib.parse import urljoin

def seo_analyze(url):
    try:
        # 發送 GET 請求
        response = requests.get(url)
        response.raise_for_status()  # 確保請求成功

        # 使用 BeautifulSoup 解析 HTML
        soup = BeautifulSoup(response.text, 'html.parser')

        # 提取標題
        title = soup.title.string if soup.title else 'No Title'
        print(f"網站標題: {title}")

        # 提取 meta 描述
        meta_description = soup.find('meta', attrs={'name': 'description'})
        description = meta_description['content'] if meta_description else 'No Description'
        print(f"網站描述: {description}")

        # 提取 H1 標籤
        h1_tags = soup.find_all('h1')
        h1_texts = [h1.get_text(strip=True) for h1 in h1_tags]
        print(f"H1 標籤: {h1_texts if h1_texts else 'No H1 Tags'}")

        # 提取內部連結
        internal_links = set()
        for a_tag in soup.find_all('a', href=True):
            href = a_tag['href']
            full_url = urljoin(url, href)
            if url in full_url:
                internal_links.add(full_url)

        print("\n內部連結:")
        for link in internal_links:
            print(link)

    except requests.RequestException as e:
        print(f"請求失敗: {e}")

# 測試範例
website_url = 'https://example.com'  # 替換為你要分析的網址
seo_analyze(website_url)

範例四、提取所有標題 (H1–H6),來分析標題結構是否符合 SEO 最佳實踐

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import requests
from bs4 import BeautifulSoup

def extract_headings(url):
    try:
        # 發送 GET 請求
        response = requests.get(url)
        response.raise_for_status()  # 確保請求成功

        # 使用 BeautifulSoup 解析 HTML
        soup = BeautifulSoup(response.text, 'html.parser')

        # 定義標題標籤列表
        heading_tags = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6']

        # 存放標題及其層級
        headings = []

        for tag in heading_tags:
            for heading in soup.find_all(tag):
                headings.append((tag.upper(), heading.get_text(strip=True)))

        if not headings:
            print("未找到任何標題標籤。")
            return

        # 輸出標題結構
        print(f"共找到 {len(headings)} 個標題標籤:\n")
        for level, text in headings:
            print(f"{level}: {text}")

        # 分析標題層級
        analyze_heading_structure(headings)

    except requests.RequestException as e:
        print(f"請求失敗: {e}")

def analyze_heading_structure(headings):
    print("\n🔍 標題結構分析:")
    previous_level = 0
    level_map = {"H1": 1, "H2": 2, "H3": 3, "H4": 4, "H5": 5, "H6": 6}

    for level, text in headings:
        current_level = level_map[level]

        # 檢查是否跳過標題層級
        if previous_level and current_level > previous_level + 1:
            print(f"⚠️ 標題層級跳躍:從 {previous_level} 跳到 {current_level} - '{text}'")

        previous_level = current_level

    print("✅ 標題層級檢查完成。")

# 測試範例
website_url = 'https://example.com'  # 請替換為你要檢查的網址
extract_headings(website_url)

範例五、SEO評分
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
import requests
from bs4 import BeautifulSoup
from urllib.parse import urljoin, urlparse

def seo_score(url):
    try:
        # 發送 GET 請求
        response = requests.get(url)
        response.raise_for_status()
        soup = BeautifulSoup(response.text, 'html.parser')

        print(f"\n🔍 正在分析網站: {url}\n")

        # 初始化分數
        score = 0
        max_score = 100
        deductions = []

        # 1. 檢查標題標籤 (Title)
        title = soup.title.string if soup.title else None
        if title:
            score += 15
        else:
            deductions.append("❌ 缺少標題標籤 (Title) (-15分)")

        # 2. 檢查 Meta 描述
        meta_desc = soup.find("meta", attrs={"name": "description"})
        if meta_desc and meta_desc.get("content"):
            score += 15
        else:
            deductions.append("❌ 缺少 Meta 描述 (-15分)")

        # 3. 檢查 H1 標籤
        h1 = soup.find("h1")
        if h1:
            score += 10
        else:
            deductions.append("❌ 缺少 H1 標籤 (-10分)")

        # 4. 檢查圖片的 Alt 屬性
        images = soup.find_all("img")
        images_with_alt = [img for img in images if img.get("alt")]
        if images and len(images_with_alt) == len(images):
            score += 15
        elif images:
            deductions.append(f"❌ 部分圖片缺少 Alt 屬性 (-10分)")
            score += 5
        else:
            deductions.append("❌ 未找到圖片 (-15分)")

        # 5. 檢查內部連結數量
        internal_links = set()
        domain = urlparse(url).netloc
        for link in soup.find_all("a", href=True):
            full_url = urljoin(url, link["href"])
            if urlparse(full_url).netloc == domain:
                internal_links.add(full_url)
        if len(internal_links) >= 3:
            score += 15
        else:
            deductions.append(f"❌ 內部連結少於 3 個 (-15分)")

        # 6. 檢查外部連結數量
        external_links = set()
        for link in soup.find_all("a", href=True):
            full_url = urljoin(url, link["href"])
            if urlparse(full_url).netloc != domain:
                external_links.add(full_url)
        if len(external_links) >= 1:
            score += 10
        else:
            deductions.append("❌ 缺少外部連結 (-10分)")

        # 7. 檢查 HTTPS
        if urlparse(url).scheme == "https":
            score += 20
        else:
            deductions.append("❌ 未使用 HTTPS (-20分)")

        # 顯示評分
        print(f"✅ SEO 總分: {score}/{max_score}\n")

        if deductions:
            print("🔻 扣分項目:")
            for deduction in deductions:
                print(deduction)
        else:
            print("🎉 恭喜!所有 SEO 檢查項目都通過了。")

    except requests.RequestException as e:
        print(f"❌ 請求失敗: {e}")

# 測試範例
website_url = 'https://example.com'  # 請替換為你要分析的網址
seo_score(website_url)

2024年6月6日 星期四

讀取EXCEL檔案計算後儲存到PDF檔

 範例:計算總交易量、總平均價、以及名字

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
from openpyxl import load_workbook
import win32com.client as win32
import os

# 載入現有的 Workbook
wb = load_workbook('AquaticTransData.xlsx')
ws = wb.active

# 計算總交易量和總交易額
TotalTradingVolume = 0  # 總交易量
TotalTransactionVolume = 0  # 總交易額
row = 2
while (ws['E' + str(row)].value != None):
    TotalTradingVolume += ws['E' + str(row)].value
    TotalTransactionVolume += ws['E' + str(row)].value * ws['F' + str(row)].value
    row+=1
ws['D'+str(row)] = '總交易量'
ws['D'+str(row+1)] = '總平均價'
ws['E'+str(row)] = TotalTradingVolume
ws['E'+str(row+1)] = TotalTransactionVolume / TotalTradingVolume
ws['E'+str(row+2)] = '王甲乙'

# 儲存到 Excel 檔案
wb.save('AquaticTransData.xlsx')
print("資料已儲存到 AquaticTransData.xlsx")

# 使用 win32com 將 Excel 轉換為 PDF
excel = win32.Dispatch('Excel.Application')
excel.Visible = False

# 打開 Excel 文件
workbook = excel.Workbooks.Open(os.getcwd()+'/'+'AquaticTransData.xlsx')

# 獲取第一個工作表
sheet = workbook.Sheets(1)

# 設置列印網格線
sheet.PageSetup.PrintGridlines = True

# 將工作表轉換為 PDF
pdf_path = os.getcwd()+'/'+'AquaticTransData.pdf'
workbook.ExportAsFixedFormat(0, pdf_path)

# 關閉 Excel 應用
workbook.Close(False)
excel.Quit()

print("PDF 檔案已儲存為 AquaticTransData.pdf")

執行結果:
資料已儲存到 AquaticTransData.xlsx
PDF 檔案已儲存為 AquaticTransData.pdf




條件過濾漁產品交易的資料儲存到EXCEL檔案中

範例:條件漁產品有田蛙和午仔魚,交易市場不含台北和台中

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import requests
import json
from openpyxl import Workbook
from openpyxl.styles import Font
# 從URL取得JSON資料
r = requests.get('https://data.moa.gov.tw/Service/OpenData/FromM/AquaticTransData.aspx')
json_data = json.loads(r.text)

# 建立一個新的Workbook
wb = Workbook()
ws = wb.active
ws.title = "漁產品交易行情"

# 寫入標題行
headers = ['交易日期', '品種代碼', '魚貨名稱', '市場名稱',  '交易量', '平均價']
ws.append(headers)

# 寫入資料
for item in json_data:
    if ('田蛙' in item['魚貨名稱'] or '午仔魚' in item['魚貨名稱']) and ('台中' not in item['市場名稱'] and '台北' not in item['市場名稱']):
        row = [
            item.get('交易日期'),
            item.get('品種代碼'),
            item.get('魚貨名稱'),
            item.get('市場名稱'),
            item.get('交易量'),
            item.get('平均價')
            ]
        ws.font = Font(color="00FF00")
        ws.append(row)

# 儲存到Excel檔案
wb.save('AquaticTransData.xlsx')

執行結果:
資料已儲存到 AquaticTransData.xlsx



自動化下載網路上圖片加上浮水印

程式:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import requests
from PIL import Image

urls = ["https://optimise2.assets-servd.host/maniacal-finch/production/animals/amur-tiger-01-01.jpg?w=1200&h=1200&auto=compress%2Cformat&fit=crop&dm=1658935145&s=704a64cbbe164087202ba90883b4b588",
       "https://t3.ftcdn.net/jpg/03/83/46/48/360_F_383464809_VAyaM0bON9NZT1UCPXghp8GhHx56QKqm.jpg",
       "https://images.ctfassets.net/rt5zmd3ipxai/2TtovnO1qnGJyPwtyuVOdU/8ddc745eca71320d2ea1d05679f81cb2/NVA-tiger.jpg?fit=fill&fm=webp&h=578&w=1070&q=72,%20https://images.ctfassets.net/rt5zmd3ipxai/2TtovnO1qnGJyPwtyuVOdU/8ddc745eca71320d2ea1d05679f81cb2/NVA-tiger.jpg?fit=fill&fm=webp&h=1156&w=2140&q=72"]
paths = ["LOGO1.png", "LOGO2.png", "LOGO3.png"]
watermark_im = Image.open("watermark.png")
for index, url in enumerate(urls):
    response = requests.get(url)
    if response.status_code == 200:
        with open(paths[index], 'wb') as fp:
            for chunk in response:
                fp.write(chunk)
        print("LOGO", index+1, "圖檔已經下載")
        im = Image.open(paths[index])
        im = im.resize((600,400))
        im.show()
        x = int(im.width - watermark_im.width)
        y = int(im.height - watermark_im.height)
        im.paste(watermark_im,(x, y),watermark_im)
        im.save(paths[index])
        im.show()
    else:
        print("錯誤! HTTP請求失敗...")

執行結果:
LOGO 1 圖檔已經下載
LOGO 2 圖檔已經下載
LOGO 3 圖檔已經下載



2024年5月9日 星期四

用Python來撰寫顯示吳郭魚在斗南市場交易情形的程式

開放資料:漁產品交易行情

1.程式碼:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
import requests
import json
r = requests.get('https://data.moa.gov.tw/Service/OpenData/FromM/AquaticTransData.aspx')
text = json.loads(r.text)
for row in text:
    if '吳郭魚' in row['魚貨名稱'] and '斗南' in row['市場名稱']:
        print ('交易日期:'+row['交易日期'])
        print ('品種代碼:'+str(row['品種代碼']))
        print ('魚貨名稱:'+row['魚貨名稱'])
        print ('市場名稱:'+row['市場名稱'])
        print ('上價:'+str(row['上價']))
        print ('中價:'+str(row['中價']))
        print ('下價:'+str(row['下價']))        
        print ('交易量:'+str(row['交易量']))
        print ('平均價:'+str(row['平均價'])) 

2.執行結果:
交易日期:1130509
品種代碼:1011
魚貨名稱:吳郭魚
市場名稱:斗南
上價:82.0
中價:76.9
下價:72.0
交易量:1559.1
平均價:76.9
交易日期:1130508
品種代碼:1011
魚貨名稱:吳郭魚
市場名稱:斗南
上價:82.0
中價:74.9
下價:67.3
交易量:1620.9
平均價:74.8
交易日期:1130507
品種代碼:1011
魚貨名稱:吳郭魚
市場名稱:斗南
上價:82.0
中價:77.2
下價:65.6
交易量:1890.9
平均價:75.8
交易日期:1130505
品種代碼:1011
魚貨名稱:吳郭魚
市場名稱:斗南
上價:83.1
中價:82.4
下價:82.0
交易量:1771.6
平均價:82.4
交易日期:1130504
品種代碼:1011
魚貨名稱:吳郭魚
市場名稱:斗南
上價:82.0
中價:81.7
下價:77.4
交易量:1989.9
平均價:80.9
交易日期:1130503
品種代碼:1011
魚貨名稱:吳郭魚
市場名稱:斗南
上價:85.2
中價:83.1
下價:82.0
交易量:1622.4
平均價:83.3
交易日期:1130502
品種代碼:1011
魚貨名稱:吳郭魚
市場名稱:斗南
上價:84.2
中價:82.0
下價:82.0
交易量:1397.8
平均價:82.4
交易日期:1130501
品種代碼:1011
魚貨名稱:吳郭魚
市場名稱:斗南
上價:82.0
中價:76.4
下價:71.5
交易量:1691.7
平均價:76.5
交易日期:1130430
品種代碼:1011
魚貨名稱:吳郭魚
市場名稱:斗南
上價:84.1
中價:81.5
下價:77.0
交易量:1725.0
平均價:81.1

2018年10月6日 星期六

Python網路爬文

在這數位時代中,網路、網站、網頁已成為日常生活中不可以缺的元素,我們生活起居經常要上網查資料,假如我們能寫一支程式來過濾網路上的資訊,這一定是很棒的一件事。本篇文章就是要用Python網路爬蟲來收集資料。

想要從網頁中取得資料就要安裝requests套件

想要解構並擷取網頁資訊就要安裝beautifulsoup4套件

import requests
r = requests.get('http://www.google.com')
print (r.text)

執行結果:

如何讀取南開科技大學的網頁內容
import requests

url = "http://www.nkut.edu.tw" 
re = requests.get(url) 
re.encoding='utf8'
print(re.text)


判斷回傳的代碼
import requests
r = requests.get('http://www.nkut.edu.tw')
print(r.status_code)
if r.status_code == requests.codes.ok:
  print("OK")

執行結果


我們來嘗試網路爬文找出南開科技大學首頁上重要資訊內容
import requests
from bs4 import BeautifulSoup

url = "http://www.nkut.edu.tw" 

re = requests.get(url) 

re.encoding='utf8'

soup = BeautifulSoup(re.text, 'html.parser')
print(soup)

print("列印出第一頁的文字")
print(soup.find('p'))   

print("\n\n列印出id是counter的文字")
print(soup.find(id='counter')) 

print("\n\n列印出全部的文字")
print(soup.find_all('p')) 

print("\n\n列印出的文字")
print(soup.find('h1'))