如何使用BeautifulSoup创建样式表外部链接?

时间:2015-10-06 05:40:23

标签: python css beautifulsoup

带有“rel”,“href”和“type”的链接,如:

<link rel="stylesheet" href="css/bootstrap.min.css" type="text/css">

为了证明我已经尝试过,这是我失败的尝试:

def add_css(self, *links):
    if links:
        new_soup = BeautifulSoup("<link>")
        for link in links:
            new_soup.attrs["rel"] = "stylesheet"
            new_soup.attrs["href"] = link
            new_soup.attrs["type"] = "text/css"
        self.soup.head.insert(0, new_soup)
        self.update_document()

输出:

<html>
<head><html><head><link/></head></html>
<title></title>
</head>
<body></body>
</html>

如您所见,那里有一个空的链接标记。顺便说一句,我试过这样的事情:

webpage.add_css("css/bootstrap.min.css")

1 个答案:

答案 0 :(得分:3)

我们直接创建:

>>> new_soup = BeautifulSoup('<link rel="stylesheet" href="css/bootstrap.min.css" type="text/css">')
>>> new_soup
<link rel="stylesheet" href="css/bootstrap.min.css" type="text/css" />
>>> type(new_soup)
<class 'BeautifulSoup.BeautifulSoup'>
>>> 

与代码相关,有很多links,因此创建link tag语句需要在for循环内

    for link in links:
        new_soup = BeautifulSoup('<link rel="stylesheet" href="%s" type="text/css">'%link)
        self.soup.head.insert(0, new_soup)
    self.update_document()

[编辑2] 通过BeautifulSoup将link标记插入html:

<强>演示

>>> from BeautifulSoup import BeautifulSoup
# Parser content by BeautifulSoup.
>>> soup = BeautifulSoup("<html><head></head><body></body></html>")
>>> soup
<html><head></head><body></body></html>
# Create New tag.
>>> new_tag = BeautifulSoup('<link rel="stylesheet" href="css/bootstrap.min.css"/>')
>>> new_tag
<link rel="stylesheet" href="css/bootstrap.min.css" />
# Insert created New tag into head tag i.e. first child of head tag.
>>> soup.head.insert(0,new_tag)
>>> soup
<html><head><link rel="stylesheet" href="css/bootstrap.min.css" /></head><body></body></html>
>>> new_tag = BeautifulSoup('<link rel="stylesheet" href="css/custom1.css"/>')
>>> new_tag
<link rel="stylesheet" href="css/custom1.css" />
>>> soup.head.insert(0,new_tag)
>>> soup
<html><head><link rel="stylesheet" href="css/custom1.css" /><link rel="stylesheet" href="css/bootstrap.min.css" /></head><body></body></html>
>>> 

[编辑3]

我认为您是从BeautifulSoup模块导入的bs4

BeautifulSoup是类,它将html内容作为参数。

创建新标记:

使用new_tag类的BeautifulSoup方法创建新标记。

使用attrs的{​​{1}}属性添加new_tagclass属性及其值。

<强>演示

href