如何解决单页应用程序中分页中的 Python Web Scraping
我目前正在研究如何在单页应用程序 (SPA) 中由 javascript 驱动的分页中使用 python 抓取 Web 内容。
例如, https://angular-8-pagination-example.stackblitz.io/
我在谷歌上搜索并发现使用 Scrapy 无法抓取 javascript / SPA 驱动的内容。 它需要使用飞溅。我是 Scrapy 和 Splash 的新手。 这是正确的吗?
另外,如何调用javascript分页方法?我检查了元素,它只是一个没有 href 和 javascript 事件的锚点。
请指教。
谢谢,
哈杰
解决方法
您需要使用 SpalshRequest 来呈现 JS。然后,您需要获取分页文本。通常,我使用带有适当正则表达式模式的 re.search 来提取相关数字。然后,您可以将它们分配给当前页面变量和总页面变量。
通常,网站会通过在 url 末尾增加 ?page=x 或 ?p=x 来移动到下一页。然后,您可以增加此值以抓取所有相关页面。
整体模式如下:
import scrapy
from scrapy_splash import SplashRequest
import re
from ..items import Item
proxy ='http//your.proxy.com:PORT'
current_page_xpath='//div[your x path selector]/text()'
last_page_xpath='//div[your other x path selector]/text()'
class spider(scrapy.Spider):
name = 'my_spider'
allowed_domains =['domain.com']
start_urls =['https://www.domaintoscrape.com/page=1']
def start_requests(self):
for url in self.start_urls:
yield scrapy.Request(url=url,callback=self.parse,meta ={'proxy':proxy})
def get_page_nbr(value):
#you may need more complex regex to get page numbers.
#most of the time they are in form "page X of Y"
#google is your friend
if re.search('\d+',value):
value = re.search('\d+',value)
value = value[0]
else:
value =None
return value
def parse(self,response):
#get last and current page from response:
last_page = page_response.xpath(last_page_xpath).get()
current_page = page_response.xpath(current_page_xpath).get()
#do something with your response
# if current page is less than last page make another request by incrmenenting the page in the URL
if current_page < last_page:
ajax_url = response.url.replace(f'page={int(current_page)}',f'page={int(current_page)+1}')
yield scrapy.Request(url=ajax_url,meta ={'proxy':proxy})
#optional
if current_page == last_page:
print(f'processed {last_page} items for {response.url}')
最后,值得一看的是 Youtube,因为有许多关于 scrapy_splash 和分页的教程。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。