python爬虫類浅入深13--scrapy基礎実戦・爬取哈理工教務オンライン公告

2304 ワード


1.サイト分析
哈理工教務オンラインを開き、教務公告ページに入り、各ページの表示量を10000などの大きな値に設定します.の
対応するサイトは次のとおりです.http://jwzx.hrbust.edu.cn/homepage/infoArticleList.do;jsessionid=0A7BC5FE8C48FB877683ABB970E4F6D6.TH?sortColumn=publicationDate&columnId=354&sortDirection=-1&pagingPage=1&pagingNumberPer=10000
つかむべき文章のタイトルのソースコードは以下の通りです.
python爬虫由浅入深13--scrapy基础实战·爬取哈理工教务在线公告_第1张图片
では、公告記事のタイトルのxpahtは:
"//ul[@class='articleList']/li/div/a/text()"

2.cmdを開き、scrapy startproject jwzxを入力
3.jwzx/jwzx/spidersを開き、新しいファイルjwzxSpiderを作成します.py
コードの作成:
import scrapy

class jwzxSpider(scrapy.Spider):
    name = 'jwzx'
    start_urls = ['http://jwzx.hrbust.edu.cn/homepage/infoArticleList.do;jsessionid=0A7BC5FE8C48FB877683ABB970E4F6D6.TH?sortColumn=publicationDate&columnId=354&sortDirection=-1&pagingPage=1&pagingNumberPer=10000']

    def parse(self, response):
        titles = response.xpath("//ul[@class='articleList']/li/div/a/text()").extract()
        urls = response.xpath("//ul[@class='articleList']/li/div/a/@href").extract()
        for i in range(len(urls)):
            print(titles[i])
            print(urls[i])
            with open("C:/Users/kfc/Desktop/jwzx.txt",'a',encoding='utf-8') as f:
                f.write(titles[i].strip()+'
'+'http://jwzx.hrbust.edu.cn/homepage/'+urls[i]+'
')

4.次にcmdに入り、プロジェクトのルートディレクトリの下でscrapy crawl jwzxを実行します(このjwzxはさっきjwzxSpider.pyファイルのnameフィールドです)
5.出力はローカルファイルに保存されます.
python爬虫由浅入深13--scrapy基础实战·爬取哈理工教务在线公告_第2张图片