我正在一个小组项目中,我们正在尝试根据颜色数量对网站设计进行排名。
我使用了一个正则表达式来解析一个我已经下载的'style.css'文件,并且使颜色递减,但是我在抓取URL方面很挣扎。我希望能够直接从用户输入的任何URL访问CSS代码。

我在编程方面还很陌生,所以很感谢我提供的帮助,因为我一直在寻找多种解决方案,但我不太了解它们,也不知道如何为我的需要重新分配它们。

最佳答案

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

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)

关于python - 如何根据用户输入动态剪贴网站以获取CSS文件?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58898929/

10-12 13:05
查看更多