一个简单的Python爬虫示例,使用`requests`和`BeautifulSoup`库,可以按照以下步骤进行:
1. 导入必要的库:
import requests
from bs4 import BeautifulSoup
2. 发送HTTP请求并获取网页内容:
url = 'https://www.example.com' 替换为要爬取的网站URL
response = requests.get(url)
3. 检查请求状态码,确保请求成功:
if response.status_code == 200:
html = response.text
else:
print('请求失败,状态码:', response.status_code)
exit()
4. 使用BeautifulSoup解析HTML内容:
soup = BeautifulSoup(html, 'html.parser')
5. 提取所需信息,例如提取所有的标题(h1标签):
titles = soup.find_all('h1')
6. 输出提取到的信息:
for title in titles:
print(title.text)
将以上代码整合到一起,就形成了一个简单的爬虫程序,可以用来抓取指定网页的标题信息。请根据实际需要修改URL和提取逻辑。