用Xpath方法完整的爬取这个页面https://www.nju.edu.cn/xww/zhxw.htm的内容
时间: 2025-04-03 10:07:25 浏览: 52
### 使用 XPath 方法爬取指定 URL 页面的内容
要完成对 `https://www.nju.edu.cn/xww/zhxw.htm` 的数据抓取,可以通过 Python 中的 `requests` 和 `lxml` 库实现。以下是完整的解决方案:
#### 1. 安装必要的依赖库
在开始之前,需要确保已安装所需的第三方库。如果尚未安装这些库,可以运行以下命令进行安装:
```bash
pip install requests lxml
```
#### 2. 编写代码逻辑
下面是一个基于 XPath 技术的完整爬虫脚本,用于从目标网页中提取所需内容。
```python
import requests
from lxml import etree
def fetch_page_content(url):
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36'
}
try:
response = requests.get(url, headers=headers)
response.encoding = response.apparent_encoding
if response.status_code == 200:
print("成功获取源代码")
return response.text
else:
print(f"请求失败,状态码: {response.status_code}")
except Exception as e:
print(f"发生异常: {e}")
def parse_with_xpath(html_content):
selector = etree.HTML(html_content)
# 提取新闻标题
titles = selector.xpath('//div[@class="list-right"]/ul/li/a/text()') # 修改为实际路径
# 提取新闻链接
links = selector.xpath('//div[@class="list-right"]/ul/li/a/@href') # 修改为实际路径
results = []
for title, link in zip(titles, links):
full_link = f"https://www.nju.edu.cn{x.strip('/')}" if not link.startswith('http') else link
results.append({"title": title.strip(), "link": full_link})
return results
if __name__ == "__main__":
url = "https://www.nju.edu.cn/xww/zhxw.htm"
html_content = fetch_page_content(url)
if html_content:
data = parse_with_xpath(html_content)
for item in data[:10]: # 打印前10条记录作为示例
print(item)
```
上述代码实现了以下几个功能:
- **发送 HTTP 请求**:通过设置合适的 User-Agent 头部信息来模拟浏览器行为[^4]。
- **HTML 解析与 XPath 数据提取**:使用 `lxml.etree` 将 HTML 文档转化为树结构,并应用 XPath 表达式定位节点[^1]。
- **处理相对链接**:对于返回的相对 URL 地址,将其拼接成绝对地址以便后续访问。
#### 3. 调整 XPath 表达式
由于不同网站的具体 DOM 结构可能有所差异,在实际操作过程中需根据目标页面调整对应的 XPath 查询语句。例如,上面提到的选择器路径 `/html/body/div[...]/a` 可能并不适用于所有情况,因此建议开发者打开目标站点查看具体标签属性后再做修改。
---
### 注意事项
当尝试爬取某些具有严格反爬机制的目标时,可能会遇到 IP 频繁被封禁等问题。此时可通过引入代理池或者延时策略等方式缓解压力。
---
阅读全文
相关推荐


















