API - 网络爬虫
API和网络爬虫都是开发中常用的工具。如果我们想通过网络爬虫去访问在线API,需要使用requests库。
以下是一个简单的示例,可以通过API获取当前时间:
import requests
response = requests.get('http://worldclockapi.com/api/json/utc/now')
data = response.json()
print(data['currentDateTime'])
如果要使用网络爬虫抓取一个网页上的数据,可以使用BeautifulSoup库来解析HTML文档,如:
import requests
from bs4 import BeautifulSoup
response = requests.get('https://example.com')
soup = BeautifulSoup(response.text, 'html.parser')
result = soup.find('div', attrs={'class': 'my-class'}).text
print(result)