我正在尝试让Scrapy抓取一个网站,但只限于符合某种模式的网页,这让我很头疼。
网站结构如下:
website.com/category/page1/
website.com/category/page2/
website.com/category/page3/
等等。
我需要它从类别开始抓取,然后按照指向另一个页面的所有链接(总共375页,当然这个数字不固定)。
问题是它在我停止之前爬过~10页,但它只返回10-15项,其中应该有200 +
这是我的代码,它无效:
class WSSpider(CrawlSpider):
name = "ws"
allowed_domains = ["website.com"]
start_urls = ["https://www.website.com/category/"]
rules = (
Rule(LinkExtractor(allow=("/level_one/page*",)), callback="parse_product", follow=True),
)
def parse_product(self, response):
sel = Selector(response)
sites = sel.css(".pb-infos")
items = []
for site in sites:
item = Website()
item["brand"] = site.css(".pb-name .pb-mname::text").extract()
item["referinta"] = site.css(".pb-name a::text").extract()
item["disponibilitate"] = site.css(".pb-availability::text").extract()
item["pret_vechi"] = site.css(".pb-sell .pb-old::text").extract()
item["pret"] = site.css(".pb-sell .pb-price::text").extract()
item["procent"] = site.css(".pb-sell .pb-savings::text").extract()
items.append(item)
#return items
f = open("output.csv", "w")
for item in items:
line = \
item["brand"][0].strip(), ";", \
item["referinta"][-1].strip(), ";", \
item["disponibilitate"][0].strip(), ";", \
item["pret_vechi"][0].strip().strip(" lei"), ";", \
item["pret"][0].strip().strip(" lei"), ";", \
item["procent"][0].strip().strip("Mai ieftin cu "), "\n"
f.write("".join(line))
f.close()
非常感谢任何帮助!
答案 0 :(得分:0)
我发现了我的(愚蠢)错误。
f = open("output.csv", "w")
实际上应该是
f = open("output.csv", "a")
答案 1 :(得分:0)
我曾经写过一个python scraper,在它关闭之前下载一个内部wiki站点 - 遇到了一个问题,我们的内部网或wiki服务器限制了我的脚本对内容的访问。我认为有一种方法可以让scrapy更慢地访问。
我遇到的另一个问题是身份验证 - 维基的某些部分需要登录才能阅读。
另一个问题是你每次都在覆盖output.csv ......
答案 2 :(得分:0)
parse_product
是异步的,请改用CsvItemExporter
。
http://doc.scrapy.org/en/latest/topics/exporters.html#csvitemexporter