帮我用Xpath爬取https://www.nju.edu.cn/xww/zhxw.htm这个网站中综合新闻的标题 想爬取的内容都在<div class="kxdt-r wl"></div>标签中
时间: 2025-04-03 08:07:39 浏览: 52
### 如何通过 XPath 爬取指定标签内的综合新闻标题
要爬取目标网站 `https://www.nju.edu.cn/xww/zhxw.htm` 中 `<div class="kxdt-r wl">` 标签下的综合新闻标题,可以按照以下方式构建 Scrapy 的 Spider 并利用 XPath 提取所需数据。
#### 构建 Scrapy Spider 和 XPath 表达式
Scrapy 是一个强大的 Python 库,用于抓取网页并提取结构化数据。以下是完整的解决方案:
1. **创建 Scrapy 项目**
首先,在命令行中初始化一个新的 Scrapy 项目:
```bash
scrapy startproject nju_news
cd nju_news
```
2. **定义 Spider 文件**
创建名为 `nju_spider.py` 的 Spider 脚本,并编写以下代码:
```python
import scrapy
class NjuSpider(scrapy.Spider):
name = 'nju'
allowed_domains = ['www.nju.edu.cn']
start_urls = ['https://www.nju.edu.cn/xww/zhxw.htm']
def parse(self, response):
# 定义 XPath 来匹配 <div class="kxdt-r wl"> 下的 a 标签
news_titles = response.xpath('//div[@class="kxdt-r wl"]/ul/li/a/text()').getall()
for title in news_titles:
yield {
'title': title.strip(), # 去除多余空白字符
}
```
3. **运行 Spider**
执行以下命令启动爬虫程序:
```bash
scrapy crawl nju -o output.json
```
上述命令会将爬取到的数据保存至 `output.json` 文件中。
4. **解释 XPath 表达式的含义**
- `//div[@class="kxdt-r wl"]`: 查找具有类名 `kxdt-r wl` 的所有 `<div>` 元素[^1]。
- `/ul/li/a`: 继续查找该 `<div>` 内部嵌套的 `<ul>`, `<li>`, 及其子节点 `<a>` 标签[^2]。
- `text()`: 获取 `<a>` 标签内部的文字内容。
- `.getall()`: 返回所有匹配项组成的列表。
5. **处理异常情况**
如果需要验证初始请求是否成功加载页面,则可以在解析函数前加入尝试捕获逻辑:
```python
try:
html = requests.get(response.url, headers={'User-Agent': 'Mozilla/5.0'})
html.encoding = html.apparent_encoding
if html.status_code != 200:
raise ValueError(f"Failed to load page with status code {html.status_code}")
except Exception as e:
self.logger.error(f"Error occurred while loading the initial URL: {e}")
```
#### 注意事项
- 确保安装了必要的依赖库(如 `requests`),可以通过 pip 工具完成安装:
```bash
pip install requests
```
- 若目标站点有反爬机制,可能需设置合理的 User-Agent 或启用代理 IP 请求头配置。
---
### 输出样例
假设上述脚本执行无误,最终生成的 JSON 数据类似于以下形式:
```json
[
{"title": "南京大学举办国际学术会议"},
{"title": "科研成果荣获国家科技进步奖"}
]
```
---
阅读全文
相关推荐



















