要获取网页内容,你可以使用Python的`requests`库发起HTTP GET请求。以下是一个简单的示例代码,展示了如何使用`requests`库获取网页内容:
import requests
发起GET请求获取网页内容
url = 'https://www.example.com'
response = requests.get(url)
检查请求是否成功
if response.status_code == 200:
输出网页内容
print(response.text)
else:
print('请求失败')
如果你需要传递参数或者设置请求头,可以在`get`方法中传递对应的参数。例如:
import requests
url = 'https://www.example.com'
params = {
'key1': 'value1',
'key2': 'value2'
}
headers = {
'User-Agent': 'Mozilla/5.0'
}
response = requests.get(url, params=params, headers=headers)
输出网页内容
print(response.text)
如果你需要解析HTML内容,可以使用`BeautifulSoup`库。以下是一个示例代码,展示了如何使用`requests`和`BeautifulSoup`获取并解析网页内容:
import requests
from bs4 import BeautifulSoup
url = 'http://example.com'
response = requests.get(url)
使用BeautifulSoup解析网页内容
soup = BeautifulSoup(response.text, 'html.parser')
获取网页标题
title = soup.title.string
print('网页标题:', title)
获取所有的链接
links = soup.find_all('a')
for link in links:
print('链接:', link.get('href'))
获取指定元素的内容
element = soup.find('div', class_='content')
print('内容:', element.text.strip())
请确保在开始之前已经安装了`requests`和`BeautifulSoup`库,可以使用以下命令进行安装:
pip install requests
pip install beautifulsoup4