国产成人精品999视频&日本一区二区亚洲人妻精品&久久久精品国产99久久精&99热这里只有成人精品国产&精品国产剧情av一区二区&成人亚洲精品久久久久app&国产精品美女高潮抽搐A片

Categories


Tags


用python寫一個爬取特定網(wǎng)站所有鏈接,并生成站點地圖的程序,生成的結果包含html和xml兩種格式

  用python寫一個爬取特定網(wǎng)站所有鏈接,并生成站點地圖的程序,生成的結果包含html和xml兩種格式

整理自網(wǎng)絡ChatGPT產(chǎn)生之內(nèi)容,文本內(nèi)容不具備參考意義,程序內(nèi)容及代碼片段有且僅有借鑒意義。

  

使用python爬蟲scrapy來實現(xiàn)

1、安裝scrapy框架: pip install scrapy

2、創(chuàng)建一個項目: scrapy startproject  project_name

3、進入項目目錄,創(chuàng)建一個spider: cd project_name && scrapy genspider spider_name website

4、在spider文件里定義start_urls,allowed_domains,并實現(xiàn)網(wǎng)頁下載和url處理器:

import scrapy
from scrapy.selector import Selector
from scrapy.http import Request

class Spider_name(scrapy.Spider):
    name = "Spider_name"
    allowed_domains = [] #  設置允許的網(wǎng)址
    start_urls = [
		 'https://www.example.com/',
    ]

    def parse(self, response):
        """
        網(wǎng)頁下載器
        """
        # 下載網(wǎng)頁
        html = response.body
        # 對下載的網(wǎng)頁進行解析
        selector = Selector(text=html)
        # 獲取當前頁所有鏈接
        list_urls = selector.xpath("http://a/@href").extract()

        for url in list_urls:
            # 避免重復爬取
            if url not in self.allowed_domains:
                yield Request(url, callback=self.parse)

    def save_result(self, list_urls):
        """
        保存抓取到的結果
        """
        # 生成html格式
        with open('urls.html', 'w+') as fp:
            fp.write("")
            for url in list_urls:
                fp.write("" + url + "
") fp.write("") # 生成xml格式 with open('urls.xml', 'w+') as fp: fp.write("") for url in list_urls: fp.write(""+url+"") fp.write("")

Public @ 2023-02-18 14:07:52 整理自網(wǎng)絡ChatGPT產(chǎn)生之內(nèi)容,文本內(nèi)容不具備參考意義,程序內(nèi)容有且僅有借鑒意義。

更多您感興趣的搜索

0.456944s