我正在尝试删除指向该网站的所有链接:https://www.formatic-centre.fr/formation/
因此,首先,我启动了此脚本只是为了测试并查看我是否可以抓取第一页的链接:
import scrapy
class LinkSpider(scrapy.Spider):
name = "link"
#allow_domains = ['https://www.formatic-centre.fr/']
start_urls = ['https://www.formatic-centre.fr/formation/']
#rules = (Rule(LinkExtractor(allow=r'formation'), callback="parse", follow= True),)
def parse(self, response):
card = response.xpath('//a[@class="title"]')
for a in card:
yield {'links': a.xpath('@href').get()}
它奏效了,我得到了这个:
[
{"links": "https://www.formatic-centre.fr/formation/les-regles-juridiques-du-teletravail/"},
{"links": "https://www.formatic-centre.fr/formation/mieux-gerer-son-stress-en-periode-du-covid-19/"},
{"links": "https://www.formatic-centre.fr/formation/dynamiser-vos-equipes-special-post-confinement/"},
{"links": "https://www.formatic-centre.fr/formation/conduire-ses-entretiens-specifique-post-confinement/"},
{"links": "https://www.formatic-centre.fr/formation/cours-excel/"},
{"links": "https://www.formatic-centre.fr/formation/autocad-3d-2/"},
{"links": "https://www.formatic-centre.fr/formation/concevoir-et-developper-une-strategie-marketing/"},
{"links": "https://www.formatic-centre.fr/formation/preparer-soutenance/"},
{"links": "https://www.formatic-centre.fr/formation/mettre-en-place-une-campagne-adwords/"},
{"links": "https://www.formatic-centre.fr/formation/utiliser-google-analytics/"}
]
但是当我要爬网所有页面时,事情变得很脏..而且我迷路了,我的脚本不再起作用了,我猜我的循环不太正确,因为我有doublon等等。
这是我的最终脚本:
import scrapy
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor
from lxml import html
class LinkSpider(scrapy.Spider):
name = "link"
#allow_domains = ['https://www.formatic-centre.fr/']
start_urls = ['https://www.formatic-centre.fr/formation/']
rules = (Rule(LinkExtractor(allow=r'formation'), callback="parse", follow= True),)
def parse(self, response):
card = response.xpath('//a[@class="title"]')
for a in card:
yield {'links': a.xpath('@href').get()}
next_page = response.xpath('.//a[@class="pagination__next btn-squae"]/@href').extract_first()
if next_page:
yield scrapy.Request(
response.urljoin(next_page),
callback=self.parse
)
也许这是我的路?我检查并再次检查以查看“下一个按钮”将好的href放在哪里,然后输入:.//a[@class="pagination__next btn-squae"]/@href
但是奇怪的是,html源中的链接没有链接到第二页,所以我很困惑。
在这里-> link
有什么想法吗?
编辑:显然我需要一些FormRequest
,我需要使用这种代码吗? ajax
答案 0 :(得分:1)
下一页将动态加载AJAX。您必须使用FormRequest
从scrapy模拟这些请求。
我建议您阅读this。
总而言之,您将不得不使用浏览器的开发人员工具来观察如何(以及在何处)发出请求,复制表格(有时还需要标头)并产生一个FormRequest
。
选择请求。附带数据是此请求的详细信息。
该矩形显示浏览器发出的请求的目的地。 下方有一个“ Response Headers”字段(可见),在该字段下方(您在图像中看不到),将有一个请求标头,这些是浏览器用作请求标头的参数。 有一个名为“请求”的选项卡,您将在其中找到浏览器用于POST请求的表单数据。
您将必须使用FormRequest并模拟您的浏览器发出的请求。首先复制表格中的参数,如果不起作用,请在请求中包含标头。
顺便说一下,这是Firefox。我提到的其他浏览器可能在不同的位置。
这里的想法是Scrapy应该模拟浏览器的行为。在大多数情况下,这是一个轻松的过程(一旦您了解自己在做什么),但有时可能会很痛苦并且需要花费大量时间,所以请放轻松。