【问题标题】:How do I dynamically scrape websites for CSS files based on user input?如何根据用户输入动态抓取网站的 CSS 文件?
【发布时间】:2020-03-12 21:35:46
【问题描述】:

我正在开展一个小组项目,我们正在尝试根据颜色数量对网站设计进行排名。 我使用正则表达式来解析我已经下载的“style.css”文件并让颜色倒计时,但我在抓取 URL 部分时遇到了困难。我希望能够直接从用户输入的任何 URL 访问 CSS 代码。

我对编程很陌生,因此我很感激提供的任何帮助,因为我一直在寻找多种解决方案,但我并不真正了解它们或如何根据我的需要重新调整它们。

【问题讨论】:

  • requests获取HTML,用bs4解析它,然后寻找<link rel="stylesheet" type="text/css" href="[CSS URL]" >这样的标签。
  • @AlexHall 您如何查找标签以及如何处理它们?

标签: python css web-scraping


【解决方案1】:

这是一个简单的示例程序,它将查找页面的所有页面内样式数据,以及查找所有链接的样式页面并打印出所有内容。这应该可以帮助您入门,但您必须将其链接到您的颜色计数系统。

import urllib.request as req
from bs4 import BeautifulSoup

url = input('enter a full website address: ')

html = req.urlopen(url) # request the initial page
soup = BeautifulSoup(html, 'html.parser')
for styles in soup.select('style'): # get in-page style tags
    print('in page style:')
    print(styles.string)

for link in soup.find_all('link', type='text/css'): # get links to external style sheets
    address = link['href'] # the address of the stylesheet
    if address.startswith('/'): # relative link
        address = url + address
    css = req.urlopen(address).read() # make a request to download the stylesheet from the address
    print('linked stylesheet')
    print(css)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-02-11
    • 2022-01-24
    • 1970-01-01
    • 1970-01-01
    • 2010-09-17
    • 2019-09-22
    相关资源
    最近更新 更多