python - 使用 BeautifulSoup 更新 HTML 文件

标签 python html beautifulsoup

我希望能够保存使用 BeautifulSoup 对 HTML 文件所做的更改。我的脚本目前能够找到 HTML 文件中包含单词“data”的所有 href,然后能够利用 Google 的 url 结果构造一个新的 href。标签值正确打印,但问题是我无法看到输出文件中反射(reflect)的这些更改,因为汤似乎没有更新。

更新以反射(reflect)工作解决方案 -

# making the soup
htmlDoc = open('test.html', "r+")
soup = BeautifulSoup(htmlDoc)

i = 0 #initialize counter

for tag in soup.findAll(href=re.compile("data")): #match for href's with keyword data
    i += 1
    print i
    print tag.get_text()    
    text = tag.get_text() + "applications"
    g = pygoogle(text)
    g.pages = 1
    # print '*Found %s results*'%(g.get_result_count())
    if "http" in g.get_first_url(): 
        print g.get_first_url()
        new_tag = soup.new_tag("a", href=g.get_first_url())
        new_tag.string = tag.get_text()
        print new_tag
        tag.replace_with(new_tag)


print "Remaining"
print i

htmlDoc.close()

html = soup.prettify(soup.original_encoding)
with open("test.html", "wb") as file:
    file.write(html)

最佳答案

您已经创建了一个新标签 new_tag = soup.new_tag("a", href=g.get_first_url()),但您尚未实际插入 new_tagHTML 代码中,您仅将其分配给变量 new_tag

您需要使用 BeatifulSoup 提供的 insert()append() 方法,以便将标签实际放置在 html 中。

或者您可以使用以下命令重新分配链接的'href':

htmlDoc = open('test.html', "r+")
soup = BeautifulSoup(htmlDoc)

i = 0 #initialize counter

for tag in soup.findAll(href=re.compile("data")): #match for href's with keyword data
    i += 1
    print i
    print tag.get_text()    
    text = tag.get_text() + "applications"
    g = pygoogle(text)
    g.pages = 1
    # print '*Found %s results*'%(g.get_result_count())
    if "http" in g.get_first_url(): 
        print g.get_first_url()
        new_tag['href'] = g.get_first_url()

关于python - 使用 BeautifulSoup 更新 HTML 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31872045/

相关文章:

html - 访问应用程序内 html 文档内的 css 类选择器

python - 如何设置 Django 应用程序的基本 URL?

Python 子进程 : how to pipe to gnuplot a command to plot a variable?

javascript - 不缩放动态固定元素

html - 将 tabindex 附加到标题

python - 使用 selenium 和 BeautifulSoup 获取页面的可见内容

python - 如何在python中设置本地DNS服务器

Python Flask jinja2 在模板中使用数学模块 sin() cos()

python - 使用 beautifulsoup 抓取 <h2> 标签

python - 我如何使用 Beautifulsoup 获取 url 地址