
1、首先,让MysqlDB初始化数据库。
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方法中,指定爬取主链接地址,使用关键词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):
    # 随机UA
    # 依赖:pip3 install fake_useragent
    ua = UserAgent().random
    request.headers = {'User-Agent': ua}
    return request
3、抓取主页标题和链接地址。
使用内置方法xpath分析数据。
def parse(self, request, response):
    # print(response.text)
    card_elements = response.xpath('//div[@class="cc-cd"]')
 
    # 过滤出对应的卡片元素【什么值得买】
    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]
 
    # 获取内部文章标题及地址
    a_elements = buy_good_element.xpath('.//div[@class="cc-cd-cb nano"]//a')
 
    for a_element in a_elements:
        # 标题和链接
        title = a_element.xpath('.//span[@class="t"]/text()').extract_first()
        href = a_element.xpath('.//@href').extract_first()
 
        # 再次下发新任务,并带上文章标题
        yield feapder.Request(href, download_midware=self.download_midware, callback=self.parser_detail_page,
                              title=title)
                        神龙|纯净稳定代理IP免费测试>>>>>>>>天启|企业级代理IP免费测试>>>>>>>>IPIPGO|全球住宅代理IP免费测试
 
                     
                


