采集策略
任務:采集四川大學公共管理學院所有的新聞資訊
策略:先分析網頁,發現網頁之間存在的關系需要從新聞動態頁面點擊進入新聞詳情頁抓取到新聞的具體內容
采集流程
- 分析網頁,確定需要采集的內容,命名實體。
- 根據實體,定位網頁上的標簽,制定采集規則
- 新建一個project -ggnews
- define items 定義四個實體的item
- 編寫代碼ggnews_1.py
- 執行爬蟲
- 最終存為json或xml
1. 確定采集目標
先進到四川大學公共管理學院的官網,發現抓取不到全部新聞,需要點擊more進入到新聞動態里。
公共管理學院首頁.png
新聞動態首頁只有12條新聞的標題和日期,點進才有所有的新聞
新聞動態首頁.png
新聞詳情頁.png
發現新聞詳情頁有需要的新聞詳情:標題、發布時間、圖片、內容,確定實體title、time、img、content。
2. 制定采集規則
以上發現要從新聞動態頁面點擊鏈接進入新聞詳情頁才能抓取到新聞的具體內容。要采集所有新聞內容,就需要先采集新聞動態的所有新聞鏈接,并且進入到新聞詳情鏈接里面抓取所有的新聞內容。
新聞動態頁的采集:
分析新聞動態首頁,用開發者工具定位鏈接的標簽
鏈接標簽.png
href.xpath(
"http://ul[@class='newsinfo_list_ul mobile_dn']/li/div/div[@class='news_c fr']/h3/a/@href")
由于新聞是分頁表示的,需要分析其下一頁表示
下一頁按鈕.png
下一頁按鈕2.png
發現其中規律,寫一個循環,將所有頁面表示出來。
next_page = response.xpath(
"http://div[@class='pager cf tr pt10 pb10 mt30 mobile_dn']/li[last()-1]/a/@href").extract_first()
if next_page is not None:
next_pages = response.urljoin(next_page)
新聞詳情頁:
找到那四個實體:
標題 時間.png
item['date'] = response.xpath('//div[@class="detail_zy_title"]/p/text()').extract()
item['title'] = response.xpath('//div[@class="detail_zy_title"]/h1/text()').extract()
內容.png
item['content'] = response.xpath("http://div[@class='detail_zy_c pb30 mb30']/p/span/text()").extract()
圖片.png
item['img'] = response.xpath('//div/img/@src').extract()
先采集新聞動態頁的全部新聞鏈接,再通過鏈接循環采集新聞的四個實體。
3.本地代碼編寫
- 新建一個project
scrapy startproject ggnews
cd /ggnews/ggnews
- define items 定義實體的item
import scrapy
class GgnewsItem(scrapy.Item):
title = scrapy.Field()
time = scrapy.Field()
content = scrapy.Field()
img = scrapy.Field()
- ggnews_1.py
import scrapy
from ggnews.items import GgnewsItem
class GgnewsSpider(scrapy.Spider):
name = "ggnews"
start_urls = [
'http://ggglxy.scu.edu.cn/index.php?c=special&sid=1',
]
def parse(self, response):
for href in response.xpath(
"http://ul[@class='newsinfo_list_ul mobile_dn']/li/div/div[@class='news_c fr']/h3/a/@href"):
url = response.urljoin(href.extract())
yield scrapy.Request(url, callback=self.parse_details)
next_page = response.xpath(
"http://div[@class='pager cf tr pt10 pb10 mt30 mobile_dn']/li[last()-1]/a/@href").extract_first()
if next_page is not None:
next_pages = response.urljoin(next_page)
yield scrapy.Request(next_pages, callback=self.parse)
def parse_details(self, response):
item = GgnewsItem()
item['title'] = response.xpath("http://div[@class='detail_zy_title']/h1/text()").extract()
item['time'] = response.xpath("http://div[@class='detail_zy_title']/p/text()").extract()
item['content'] = response.xpath("http://div[@class='detail_zy_c pb30 mb30']/p/span/text()").extract()
item['img'] = response.xpath('//div/img/@src').extract()
yield item
- 執行爬蟲
scrapy crawl ggnews -o ggnews.xml
執行.png
最終結果分析
以xml的形式得到了所有新聞的鏈接、標題、詳情、圖片、發布時間,但是出現亂碼,應該是要在代碼中加上什么轉碼的代碼,還有兩條信息報錯,也沒有來得及去分析。
結果亂碼.png