Python爬虫示例代码
封面图
•
2025-11-01
•
Python
267
0
0
0
当然可以!以下是一个简单的 **Python 爬虫示例**,使用 `requests` 和 `BeautifulSoup` 库来抓取网页内容并提取信息。这个例子是抓取一个网页的标题和所有链接。 --- ## 🌐 示例:抓取网页标题和链接 ### 1. 安装依赖库(如果还没有安装) ```bash pip install requests beautifulsoup4 ``` --- ### 2. Python 爬虫代码示例 ```python import requests from bs4 import BeautifulSoup # 目标网址 url = 'https://example.com' # 发送 HTTP 请求 response = requests.get(url) # 检查请求是否成功 if response.status_code == 200: # 解析 HTML 内容 soup = BeautifulSoup(response.text, 'html.parser') # 获取网页标题 title = soup.title.string print(f"网页标题: {title}") # 提取所有链接 print("\n所有链接:") for link in soup.find_all('a'): href = link.get('href') if href: print(href) else: print(f"请求失败,状态码: {response.status_code}") ``` --- ## ✅ 示例说明 - `requests.get(url)`:发送 GET 请求获取网页内容。 - `BeautifulSoup(response.text, 'html.parser')`:解析 HTML 内容。 - `soup.title.string`:获取网页标题。 - `soup.find_all('a')`:查找所有 `<a>` 标签,提取其中的 `href` 属性。 --- ## 🧠 注意事项 - 爬虫需遵守目标网站的 `robots.txt` 文件规则(如 `https://example.com/robots.txt`)。 - 不要频繁请求,避免对服务器造成压力。 - 可以添加 `headers` 来模拟浏览器访问,防止被识别为爬虫: ```python headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36' } response = requests.get(url, headers=headers) ``` --- ## 📦 其他常用库 | 库名 | 功能 | |----------------|------------------------------| | `requests` | 发送 HTTP 请求 | | `BeautifulSoup`| 解析 HTML/XML 内容 | | `lxml` | 更快的 HTML 解析器 | | `scrapy` | 强大的爬虫框架(适合大型项目)| --- 如果你有具体的网站或目标数据,我可以帮你写更针对性的代码!需要吗?
下一篇:
vscode python print 输出窗口中文乱码
标题录入,一次不能超过6条
留言
评论