【发布时间】:2021-08-09 03:37:28
【问题描述】:
我正在尝试首先爬取该网站的主页,以获取指向每年表格的链接。然后我想抓取每个站点,同时保持每年的记录。
到目前为止,我的蜘蛛构造为:
div = response.xpath('//*[@id="sidebar"]/div[1]/nav/ul/li[5]/div')
hrefs = div.xpath('*//a').extract()
splits = {}
for href in hrefs:
split = href.split('"')
link = split[1]
date = split[2]
clean_date = "".join(re.findall("[^><a/]",date))
clean_link = "http://www.ylioppilastutkinto.fi" + str(link)
splits[clean_date] = clean_link
然后,我想使用以下逻辑浏览此文件中的每个链接并爬取它们:
table = resp.xpath('//*[@id="content"]/table/tbody')
rows = table.xpath('//tr')
data_dict = {"Category":
[w3lib.html.remove_tags(num.get()) for num in rows[0].xpath('td')[1:]]
}
for row in rows[1:]:
data = row.xpath('td')
title = w3lib.html.remove_tags(data[0].get())
nums = [w3lib.html.remove_tags(num.get()) for num in data[1:]]
data_dict[title] = nums
我的问题是我找不到有效的方法。在 url 上调用 scrapy.Request 会返回一个仅包含内容 <html></html> 的响应。如果有一种方法可以使响应对象类似于 Scrapy shell 中的 fetch 命令给出的对象,那将是理想的,因为我已将选择逻辑基于使用该命令进行测试。
编辑:
这是到目前为止的整个蜘蛛
这个想法是运行第一个 for 循环以获取链接,然后运行第二个 for 循环以从所述链接中提取表。
import scrapy
import regex as re
from scrapy.http import HtmlResponse
import w3lib.html
class MainSpider(scrapy.Spider):
name = 'links'
allowed_domains = ['www.ylioppilastutkinto.fi/ylioppilastutkinto/pisterajat']
start_urls = ['https://www.ylioppilastutkinto.fi/ylioppilastutkinto/pisterajat/']
def parse(self, response):
div = response.xpath('//*[@id="sidebar"]/div[1]/nav/ul/li[5]/div')
hrefs = div.xpath('*//a').extract()
splits = {}
for href in hrefs:
split = href.split('"')
link = split[1]
date = split[2]
clean_date = "".join(re.findall("[^><a/]",date))
clean_link = "http://www.ylioppilastutkinto.fi" + str(link)
splits[clean_date] = clean_link
for date,url in splits.items():
resp = HtmlResponse(url)
table = resp.xpath('//*[@id="content"]/table/tbody')
rows = table.xpath('//tr')
data_dict = {"Category":[w3lib.html.remove_tags(num.get()) for num in rows[0].xpath('td')[1:]]}
for row in rows[1:]:
data = row.xpath('td')
title = w3lib.html.remove_tags(data[0].get())
nums = [w3lib.html.remove_tags(num.get()) for num in data[1:]]
data_dict[title] = nums
yield {
'Date': date,
'Scores': data_dict}
【问题讨论】:
-
不清楚您从哪个网址开始?你能发布你的完整蜘蛛吗?
-
fetch所做的是使用scrapy.Request请求 URL。你能展示一下你目前掌握的蜘蛛代码吗? -
我添加了蜘蛛的其余部分。
-
您需要
yield和Request。你做过scrapytutorial吗?
标签: python html web-scraping xpath scrapy