【问题标题】:Is there a way to extract CSS from a webpage using BeautifulSoup?有没有办法使用 BeautifulSoup 从网页中提取 CSS?
【发布时间】:2020-12-31 03:10:00
【问题描述】:

我正在做一个需要我查看网页的项目,但要进一步使用 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/

【问题讨论】:

    标签: python html python-3.x web-scraping beautifulsoup


    【解决方案1】:

    如果您的目标是真正解析 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 内容中。)

    这应该让你开始。

    【讨论】:

      猜你喜欢
      • 2022-07-18
      • 2020-10-09
      • 1970-01-01
      • 2020-05-14
      • 1970-01-01
      • 2017-08-19
      • 2020-03-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多