Pyhon网络爬虫学习笔记—抓取本地网页(一,互联网寒冬公司倒闭后
warning:
这篇文章距离上次修改已过204天,其中的内容可能已经有所变动。
import requests
# 获取本地HTML页面的函数
def get_local_html(file_path):
with open(file_path, 'r', encoding='utf-8') as file:
html_content = file.read()
return html_content
# 使用requests库获取网络资源的函数
def get_network_resource(url):
try:
response = requests.get(url)
if response.status_code == 200:
return response.text
else:
return None
except requests.exceptions.RequestException:
return None
# 测试获取本地HTML页面的函数
local_html = get_local_html('example.html')
print(local_html)
# 测试使用requests库获取网络资源的函数
network_html = get_network_resource('https://www.example.com')
if network_html:
print(network_html)
else:
print('Failed to retrieve the network resource.')
这段代码展示了如何使用Python读取本地HTML文件和使用requests库获取网络上的HTML内容。get_local_html
函数用于打开并读取本地文件,而get_network_resource
函数用于发送HTTP GET请求并获取响应内容。两个函数都有错误处理逻辑,以防止发生异常。
评论已关闭