from bs4 import BeautifulSoup
with open('index.html', 'r') as file:
fcontent = file.read()
sp = BeautifulSoup(fcontent, 'html.parser')
t = 'new_text_for_replacement'
# replace the paragraph using `replace_with` method
sp.find(itemprop='someprop').replace_with(t)
# open another file for writing
with open('output.html', 'w') as fp:
# write the current soup content
fp.write(sp.prettify())
如果要替换段落的内容而不是段落元素本身,可以设置.string属性。
sp.find(itemprop='someprop').string = t
赞0收藏0评论0分享
用户回答回答于 2018-07-26
问题取决于你搜索标准的方式,尝试更改以下代码:
print(sp.replace(sp.find(itemprop="someprop").text,t))
对此:
print(sp.replace(sp.find({"itemprop":"someprop"}).text,t))
# coding:utf-8
from bs4 import BeautifulSoup
import requests
import os
url = 'https://'
r = requests.get(url)
demo = r.text # 服务器返回响应
soup = BeautifulSoup(demo, "html.parser")
"""
demo 表示被解析的html格式的内容
html.parser表示解析用的解析器
"""
# 输出响应的html对象
ab = list()
with open("D:\\temp\\mii.txt","w+",encoding="utf-8") as xxx:
for mi in soup.find_all('a'):
ab.append(mi.prettify()) # 使用prettify()格式化显示输出
#xxx.writelines(str(mi))
xxx.writelines(ab)
xxx.close()
之前在北京买房,谁想房价开始疯长,链家的房价等数据分析只给了一小部分,远远不能满足自己的需求。于是晚上花了几个小时的时间写了个爬虫,爬下了北京所有的小区信息及北京所有小区的所有历史成交记录。gevent是一个python的并发库,它为各种并发和网络相关的任务提供了整洁的API。gevent中用到的主要模式是greenlet,它是以C扩展模块形式接入Python的轻量级协程。 greenlet全部运行在主程序操作系统进程的内部,但它们被协作式地调度。
实战
通过用gevent把异步访问得到的数据提取出来。
在有道词典搜索框输入“hello”按回车。观察数据请求情况观察有道的url构建。