簡體   English   中英

有沒有辦法使用 BeautifulSoup 從網頁中提取 CSS?

[英]Is there a way to extract CSS from a webpage using BeautifulSoup?

我正在處理一個需要我查看網頁的項目,但要進一步使用 HTML,我必須完整地查看它,而不是將其視為與圖片混合的一堆線條。 有沒有辦法使用 BeautifulSoup 解析 CSS 和 HTML?

這是我的代碼:

from bs4 import BeautifulSoup


def get_html(url, name):
    r = requests.get(url)
    r.encoding = 'utf8'
    return r.text


link = 'https://www.labirint.ru/books/255282/'
with open('labirint.html', 'w', encoding='utf-8') as file:
    file.write(get_html(link, '255282'))

警告:頁面: https : //www.labirint.ru/books/255282/重定向到https://www.labirint.ru/books/733371/

如果您的目標是真正解析 css:

美麗的湯將拉動整個頁面 - 它確實包括標題、樣式、腳本、css 和 js 中的鏈接等。我之前使用過 pythonCodeArticle 中的方法,並針對您提供的鏈接重新測試了它。

import requests
from bs4 import BeautifulSoup as bs
from urllib.parse import urljoin

# URL of the web page you want to extract
url = "ENTER YOUR LINK HERE"

# initialize a session & set User-Agent as a regular browser
session = requests.Session()
session.headers["User-Agent"] = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36"

# get the HTML content
html = session.get(url).content

# parse HTML using beautiful soup
soup = bs(html, "html.parser")
print(soup)

通過查看soup輸出(很長,這里就不貼了)..可以看到是一個完整的頁面。 只需確保粘貼您的特定鏈接

現在,如果您想解析結果以獲取所有 css url.... 您可以添加以下內容:(我仍在使用上面描述得非常好的 python 代碼文章鏈接中的部分代碼)

# get the CSS files
css_files = []
for css in soup.find_all("link"):
    if css.attrs.get("href"):
        # if the link tag has the 'href' attribute
        css_url = urljoin(url, css.attrs.get("href"))
        css_files.append(css_url)
print(css_files)

輸出 css_files 將是所有 css 文件的列表。 您現在可以分別訪問它們並查看正在導入的樣式。

注意:這個特定的站點混合了與 html 內聯的樣式(即,它們並不總是使用 css 來設置樣式屬性……有時樣式位於 html 內容中。)

這應該讓你開始。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM