您好,登錄后才能下訂單哦!
這篇文章給大家介紹怎么在python中使用feapde實(shí)現(xiàn)一個(gè)爬蟲,內(nèi)容非常詳細(xì),感興趣的小伙伴們可以參考借鑒,希望對大家能有所幫助。
Python是一種跨平臺的、具有解釋性、編譯性、互動(dòng)性和面向?qū)ο蟮哪_本語言,其最初的設(shè)計(jì)是用于編寫自動(dòng)化腳本,隨著版本的不斷更新和新功能的添加,常用于用于開發(fā)獨(dú)立的項(xiàng)目和大型項(xiàng)目。
1、首先,讓MysqlDB初始化數(shù)據(jù)庫。
from feapder.db.mysqldb import MysqlDB class TophubSpider(feapder.AirSpider): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.db = MysqlDB()
2、在start_requests方法中,指定爬取主鏈接地址,使用關(guān)鍵詞download_midware配置。
import feapder from fake_useragent import UserAgent def start_requests(self): yield feapder.Request("https://tophub.today/", download_midware=self.download_midware) def download_midware(self, request): # 隨機(jī)UA # 依賴:pip3 install fake_useragent ua = UserAgent().random request.headers = {'User-Agent': ua} return request
3、抓取主頁標(biāo)題和鏈接地址。
使用內(nèi)置方法xpath分析數(shù)據(jù)。
def parse(self, request, response): # print(response.text) card_elements = response.xpath('//div[@class="cc-cd"]') # 過濾出對應(yīng)的卡片元素【什么值得買】 buy_good_element = [card_element for card_element in card_elements if card_element.xpath('.//div[@class="cc-cd-is"]//span/text()').extract_first() == '什么值得買'][0] # 獲取內(nèi)部文章標(biāo)題及地址 a_elements = buy_good_element.xpath('.//div[@class="cc-cd-cb nano"]//a') for a_element in a_elements: # 標(biāo)題和鏈接 title = a_element.xpath('.//span[@class="t"]/text()').extract_first() href = a_element.xpath('.//@href').extract_first() # 再次下發(fā)新任務(wù),并帶上文章標(biāo)題 yield feapder.Request(href, download_midware=self.download_midware, callback=self.parser_detail_page, title=title)
關(guān)于怎么在python中使用feapde實(shí)現(xiàn)一個(gè)爬蟲就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學(xué)到更多知識。如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。