【问题标题】:How to convert a String into a BeautifulSoup object?如何将字符串转换为 BeautifulSoup 对象?
【发布时间】:2016-10-26 03:31:28
【问题描述】:

我正在尝试抓取一个新闻网站,我需要更改一个参数。我用下一个代码替换它:

while i < len(links):
    conn = urllib.urlopen(links[i])
    html = conn.read()
    soup = BeautifulSoup(html)
    t = html.replace('class="row bigbox container mi-df-local locked-single"', 'class="row bigbox container mi-df-local single-local"')
    n = str(t.find("div", attrs={'class':'entry cuerpo-noticias'}))
    print(p)

问题是“t”类型是字符串,带有属性的查找只适用于类型&lt;class 'BeautifulSoup.BeautifulSoup'&gt;。你知道如何将“t”转换为那种类型吗?

【问题讨论】:

    标签: python beautifulsoup web-crawler html-parsing


    【解决方案1】:

    只需在解析之前进行替换

    html = html.replace('class="row bigbox container mi-df-local locked-single"', 'class="row bigbox container mi-df-local single-local"')
    soup = BeautifulSoup(html, "html.parser")
    

    请注意,也可以(我什至会说首选)解析 HTML,定位元素并修改 @987654323 的属性 @实例,例如:

    soup = BeautifulSoup(html, "html.parser")
    for elm in soup.select(".row.bigbox.container.mi-df-local.locked-single"):
        elm["class"] = ["row", "bigbox", "container", "mi-df-local", "single-local"]
    

    请注意,class 是一个特殊的 multi-valued attribute - 这就是我们将值设置为单个类列表的原因。

    演示:

    from bs4 import BeautifulSoup
    
    html = """
    <div class="row bigbox container mi-df-local locked-single">test</div>
    """
    
    soup = BeautifulSoup(html, "html.parser")
    for elm in soup.select(".row.bigbox.container.mi-df-local.locked-single"):
        elm["class"] = ["row", "bigbox", "container", "mi-df-local", "single-local"]
    
    print(soup.prettify())
    

    现在看看div 元素类是如何更新的:

    <div class="row bigbox container mi-df-local single-local">
     test
    </div>
    

    【讨论】:

    • 你一定一直在等这个;)
    • 什么是html,你用的什么库?
    猜你喜欢
    • 1970-01-01
    • 2021-02-03
    • 2018-07-19
    • 2019-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多