Python入门:编写简单网页爬虫

在信息爆炸的时代,网页爬虫成为了获取网络数据的重要工具。本文将带你一步步用Python编写一个简单的网页爬虫,助你轻松抓取网页内容。

Python入门:编写简单网页爬虫

准备工作

首先,确保你已经安装了Python环境。接下来,我们需要安装两个常用的库:requests和BeautifulSoup。打开终端或命令提示符,运行以下命令:

pip install requests beautifulsoup4

编写爬虫代码

导入库

在Python文件中,首先导入所需的库:

import requests
from bs4 import BeautifulSoup

发送请求

使用requests库向目标网页发送请求,获取网页内容:

url = 'https://example.com'
response = requests.get(url)

解析网页

使用BeautifulSoup库解析获取到的网页内容:

soup = BeautifulSoup(response.text, 'html.parser')

提取数据

假设我们想提取网页中的所有标题(<h1>标签),可以这样做:

titles = soup.find_all('h1')
for title in titles:
    print(title.text)

完整代码

将上述步骤整合在一起,得到一个完整的爬虫代码:

import requests
from bs4 import BeautifulSoup

def fetch_webpage(url):
    response = requests.get(url)
    if response.status_code == 200:
        return response.text
    else:
        print(f"Error: Unable to fetch webpage, status code {response.status_code}")
        return None

def parse_titles(html):
    soup = BeautifulSoup(html, 'html.parser')
    titles = soup.find_all('h1')
    for title in titles:
        print(title.text)

def main():
    url = 'https://example.com'
    html = fetch_webpage(url)
    if html:
        parse_titles(html)

if __name__ == "__main__":
    main()

进阶技巧

处理异常

在实际应用中,网络请求可能会遇到各种异常。我们可以添加异常处理来增强代码的健壮性:

try:
    response = requests.get(url)
    response.raise_for_status()
except requests.exceptions.HTTPError as e:
    print(f"HTTP Error: {e}")
except requests.exceptions.RequestException as e:
    print(f"Request Exception: {e}")

设置请求头

有些网站会根据请求头判断是否为爬虫访问,我们可以通过设置请求头来模拟浏览器访问:

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'
}
response = requests.get(url, headers=headers)

存储数据

抓取到的数据可以存储到文件中,以便后续使用:

with open('titles.txt', 'w') as file:
    for title in titles:
        file.write(title.text + '\n')

通过本文的介绍,你已经掌握了用Python编写简单网页爬虫的基本方法。从发送请求到解析网页,再到数据提取和存储,每一步都简洁明了。当然,爬虫的世界博大精深,更多高级技巧等待你去探索。希望这篇文章能为你打开爬虫编程的大门,助你在数据获取的路上越走越远。

Happy Coding! 🐍🕷️

你可能想看:
« 上一篇
下一篇 »

相关推荐

python爬虫教程PDF,Python爬虫书PDF

2026年09月02日

31阅读

外国教程python,python编程教学视频

2026年09月02日

25阅读

python简明教程沈洁元,python详细基础教程

2026年09月02日

21阅读

python库包教程,python 包

2026年09月02日

27阅读

python教程大全集,python教程600集

2026年09月02日

26阅读

python入门教程完整版,python零基础入门全套教程视频

2026年09月02日

22阅读