使用刮Selenium时处理分页(POST 请求)



我正在尝试抓取以下网站:

https://www.getwines.com/main.asp?request=search&type=w&s1=s9818865857&fbclid=IwAR3yF9x1X7sdPYgsfl4vF1oNF7GNoF1pSov4lwJLEeeTYFGevBTfRKOPBmo

我成功地抓取了第一页,但我无法进入下一页。这有两个原因:

  1. 检查next_page按钮时,我没有得到相对或绝对 网址。相反,我得到了JavaScript:getPage(2)我不能用来跟踪链接

  2. 下一页按钮链接可以通过(//table[@class='tbl_pagination']//a//@href)[11]访问,当 在第一页上,但从第 2 页及以后,下一页按钮是第 12 项, 即(//table[@class='tbl_pagination']//a//@href)[12]

所以最终我的问题是,我如何有效地转到所有后续页面并抓取数据。

这可能很容易解决,但我是网络抓取的初学者,因此任何反馈都值得赞赏。 请参阅下面的代码。

感谢您的帮助。

**
import scrapy
from scrapy_selenium import SeleniumRequest
class WinesSpider(scrapy.Spider):
name = 'wines'

def start_requests(self):
yield SeleniumRequest(
url='https://www.getwines.com/category_Wine',
wait_time=3,
callback=self.parse
)
def parse(self, response):
products = response.xpath("(//div[@class='layMain']//tbody)[5]/tr ")
for product in products:
yield {
'product_name': 
product.xpath(".//a[@class='Srch-producttitle']/text()").get(),
'product_link': 
product.xpath(".//a[@class='Srch-producttitle']/@href").get(),
'product_actual_price': 
product.xpath(".//td//td[3]//td/span[2]/text()").get(),
'product_price_onsale': 
product.xpath(".//td//td[3]//td/span[4]/text()").get()
}
#next_page = response.xpath("(//table[@class='tbl_pagination']//a//@href)[11]").get()
#if next_page:
#    absolute_url = f"'https://www.getwines.com/category_Wine"**

请参阅下面回答上述问题的代码。

简而言之,我更改了代码的结构,现在它运行良好。一些评论:

  1. 首先,将页面的所有内容保存在一个列表中
  2. 在while-try循环的末尾使用"except NoSuchElementException"很重要 --> 在添加此内容之前,代码一直失败,因为一旦到达最后一页,它就不知道该怎么做。
  3. 访问存储的链接(响应)的内容。

总而言之,我认为在将Selenium与Scrapy集成时,以这种方式构建您的Scrapy代码效果很好。但是,由于我是网页抓取的初学者,因此有关如何有效地将Selenium与Scrapy集成的任何其他反馈将不胜感激。

# -*- coding: utf-8 -*-
import scrapy
from scrapy import Selector
from scrapy_selenium import SeleniumRequest
from selenium.common.exceptions import NoSuchElementException
class WinesSpider(scrapy.Spider):
name = 'wines'
responses = []
def start_requests(self):
yield SeleniumRequest(
url='https://www.getwines.com/category_Wine',
callback=self.parse
)
def parse(self, response):
driver = response.meta['driver']
intial_page = driver.page_source
self.responses.append(intial_page)
found = True
while found:
try:
next_page = driver.find_element_by_xpath("//b[text()= '>>']/parent::a")
href = next_page.get_attribute('href')
driver.execute_script(href)
driver.implicitly_wait(2)
self.responses.append(driver.page_source)

except NoSuchElementException:
break
for resp in self.responses:
r = Selector(text=resp)
products = r.xpath("(//div[@class='layMain']//tbody)[5]/tr")
for product in products:
yield {
'product_name':
product.xpath(".//a[@class='Srch-producttitle']/text()").get(),
'product_link':
product.xpath(".//a[@class='Srch-producttitle']/@href").get(),
'product_actual_price':
product.xpath(".//span[@class='RegularPrice']/text()").get(),
'product_price_onsale':
product.xpath(".//td//td[3]//td/span[4]/text()").get()
}

最新更新