我正在尝试将我的selenium web scraper转换为scrapy,因为selenium也不是主要用于web scraping。
我刚开始写,就遇到了一个障碍。我的代码如下。
import scrapy
from scrapy.crawler import CrawlerProcess
from pathlib import Path
max_price = "110000"
min_price = "65000"
region_code = "5E430"
class QuotesSpider(scrapy.Spider):
name = "quotes"
def start_requests(self):
url = "https://www.rightmove.co.uk/property-for-sale/find.html?locationIdentifier=REGION%" + region_code + "&minBedrooms=2&maxPrice=" + max_price + "&minPrice=" + min_price + "&propertyTypes=detached" + \
"%2Csemi-detached%2Cterraced&primaryDisplayPropertyType=houses&includeSSTC=false&mustHave=&dontShow=sharedOwnership%2Cretirement&furnishTypes=&keywords="
yield scrapy.Request(url=url, callback=self.parse)
def parse(self, response):
work_path = "C:/Users/Cristi/Desktop/Scrapy_ROI_work_area/"
no_of_pages = response.xpath('//span[@class = "pagination-pageInfo"]').getall()
with open(Path(work_path, "test.txt"), 'wb') as f:
f.write(response.body)
with open(Path(work_path, "extract.txt"), 'wb') as g:
g.write(no_of_pages)
self.log('Saved file test.txt')
process = CrawlerProcess()
process.crawl(QuotesSpider)
process.start()
我的障碍是response.body不包含xpath表达式/span[@class = "pagination-pageInfo"]所寻求的元素,但网站确实有这个元素。我对网站的内部运作不甚了解,也不是专业的程序员......很不幸。有谁能帮助我了解发生了什么事?
首先你要明白,你在浏览器中看到的东西和服务器实际发送给你的东西是有很大区别的。
服务器,除了HTML之外,大多数情况下是向你发送JavaScript代码,这些代码在运行时对HTML本身有影响。
例如,你对一个页面做的第一个GET,它可以给你一个空表和一些JavaScript代码。那段代码就负责打入数据库,并填充表格。如果你想单单用Scrapy去搜刮那个网站,就会失败,因为Scrapy没有一个能够解析代码的JavaScript引擎。
这是你在这里的情况,对于大多数你将尝试抓取的页面来说,也将是你的情况。
你需要一些东西来渲染页面中的代码。Scrapy的最佳选择是Splash。
https:/github.comscrapinghubsplash。
这是一个无头和可脚本的浏览器,你可以用Scrapy插件。它由Scrapinghub (Scrapy的创建者)维护,所以它的效果会很好。