如何解决从 URL Python 读取和解析 HTML - 高效的内存使用
我正在尝试使用具有高效内存使用的 python 读取 html(来自 URL 而不是来自文件)。 目前我正在通过以下方式阅读 html:
try:
with requests.get(input_url) as request:
request.raise_for_status()
soup = BeautifulSoup(request.content)
for paragraph in (''.join(s.findAll(text=True)) for s in soup.findAll('p')):
process(paragraph.split())
except requests.exceptions.RequestException as e:
# A serious problem happened,like an SSLError or InvalidURL
print("Error: {}".format(e))
return E_ERROR
但这还不够好,我想分块阅读html,而不是一次全部阅读,中间不剪任何段落。 我需要所有段落的全文。 我试图使用这样的东西:
response = url_opener.open(input_url)
while True:
chunk = response.read(chunk_size)
if not chunk:
break
soup = BeautifulSoup(chunk)
for paragraph in (''.join(s.findAll(text=True)) for s in soup.findAll('p')):
process(paragraph.split())
但是它在中间切掉了段落,然后 BeautifulSoup 无法识别它,然后我丢失了文本。
请帮我找到一个很好的解决方案。 非常感谢。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。