用Python对http://plap.mil.cn/freecms/site/juncai/cggg/index.html进行爬虫
时间: 2023-07-06 13:43:11 浏览: 72
好的,我可以为您提供一个基本的Python爬虫代码,用于爬取http://plap.mil.cn/freecms/site/juncai/cggg/index.html 页面上的内容。请注意,网站的访问频率和数据使用必须遵守相关法律法规和网站规定,本代码仅供学习和参考使用。
```python
import requests
from bs4 import BeautifulSoup
url = 'http://plap.mil.cn/freecms/site/juncai/cggg/index.html'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
for item in soup.select('.list li'):
title = item.select_one('a').text.strip()
date = item.select_one('.date').text.strip()
link = item.select_one('a')['href']
print(title, date, link)
```
这段代码使用了Requests库和BeautifulSoup库,首先发送了一个GET请求获取页面的HTML代码,然后使用BeautifulSoup解析页面的HTML代码,最后遍历页面上所有的列表项,并输出每个列表项的标题、日期和链接。您可以根据您自己的需求进行修改和扩展。
相关问题
以上问题如何更改
请参考以下代码,修改后应该可以正常发送请求了:
```python
# -*- coding: utf-8 -*-
import scrapy
from ..items import NpmItem
h = {
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36 Edg/113.0.1774.57'
}
class StartSpiderSpider(scrapy.Spider):
name = 'start_spider'
allowed_domains = ['www.plap.cn']
start_urls = ['https://www.plap.cn/index/selectIndexNewsByTypeId.html?page=1&id=110&title=']
def parse(self, response):
list_li = response.xpath('/html/body/div[3]/div[2]/ul/li')
for i in list_li:
items = NpmItem()
items['title'] = i.xpath('./a/@title').get()
items['time'] = i.xpath('./span/text()').get()
href = i.xpath('./a/@href').get()
url = response.urljoin(href)
yield scrapy.Request(url=url, headers=h, callback=self.detail, meta={'item': items})
# 继续访问下一页
next_page = response.xpath('//a[@class="next-page"]/@href')
if next_page:
next_url = response.urljoin(next_page.get())
yield scrapy.Request(url=next_url, headers=h, callback=self.parse)
def detail(self, response):
items = response.meta['item']
detail_url = response.xpath('/html/body/div[3]/div/div[2]/img/@src').get()
if detail_url:
detail_url = response.urljoin(detail_url)
items['detail'] = detail_url
yield items
```
修改内容:
1. allowed_domains 修改为 ['www.plap.cn']。
2. start_urls 放开注释。
3. 在 parse 函数中将 items 对象的创建移到 for 循环内,每个新闻的 title 和 time 都对应一个新的 items 对象。
4. 在 parse 函数中,加入对下一页的访问,避免只访问第一页。
5. 在 detail 函数中,使用 response.meta['item'] 获取传递的 items 对象,修正了之前的错误。
6. 在 detail 函数中,使用 response.urljoin() 方法将相对路径转换成绝对路径。