0


使用Selenium与Scrapy处理动态加载网页内容的解决方法

博客正文(包含详细注释)

引言

在爬虫技术领域,处理动态加载的网页内容常常是一项挑战,尤其是对于那些通过用户滚动或其他交互动态加载更多内容的网站。本文将介绍如何结合使用Selenium和Scrapy来有效处理这类网页。

初探Selenium与Scrapy的结合

首先,我们探索如何使用Selenium在Scrapy中间件中处理动态加载内容的网页。关键在于模拟用户滚动行为,以加载并捕获所有内容。

defprocess_response(self, request, response, spider):
    driver = spider.driver
    # 检查请求的URL是否在我们的目标列表中if request.url in spider.page_url:
        driver.get(request.url)# 使用Selenium打开页面# 等待页面初步加载完成
        time.sleep(3)# 示例等待时间,可能需要根据实际页面调整# 获取当前页面的高度
        last_height = driver.execute_script("return document.body.scrollHeight")whileTrue:# 滚动到页面底部
            driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")# 等待页面可能出现的新内容加载
            time.sleep(3)# 重新获取新的页面高度
            new_height = driver.execute_script("return document.body.scrollHeight")# 如果高度不再改变,说明到达了页面底部if new_height == last_height:break
            last_height = new_height  # 更新高度,用于下次比较# 获取完整的页面源代码
        text = driver.page_source
        # 创建新的HtmlResponse并返回return HtmlResponse(url=request.url, body=text, encoding='utf-8', request=request)# 如果URL不在目标列表中,返回原始响应return response
完整的Scrapy爬虫实例

下面是一个使用Selenium和Scrapy爬取网易新闻的示例。

import scrapy
from selenium.webdriver import Chrome, ChromeOptions
from selenium.webdriver.chrome.options import Options

classWySpider(scrapy.Spider):
    name ="wy"# 爬虫名称
    start_urls =["https://news.163.com/domestic/"]# 起始URL# Selenium配置
    opt = Options()
    opt.add_argument('--headless')# 添加headless参数,指定浏览器在无界面模式下运行,即没有用户界面或可视化界面的情况下。
    opt.add_argument('--disable-gpu')# 禁用GPU加速
    opt.add_argument('--window-size=4000,1600')# 设置浏览器窗口大小
    opt.add_experimental_option('excludeSwitches',['enable-automation'])# 防止网站识别出自动化测试
    driver = Chrome(options=opt)# 创建Chrome驱动

    href_index =[1,2]# 指定要处理的链接索引
    page_url =[]# 存储目标URL地址# 处理起始URL的响应defparse(self, resp,**kwargs):# 提取链接
        href_list = resp.xpath('/html/body/div/div[3]/div[2]/div[2]/div/ul/li/a/@href').extract()for i inrange(len(href_list)):if i in self.href_index:# 如果链接在指定索引中,添加到目标列表并发起请求
                self.page_url.append(href_list[i])yield scrapy.Request(url=href_list[i], callback=self.parse_detail)# 处理获取的新闻类别链接defparse_detail(self, resp,**kwargs):# 提取详细页面的链接
        detail_url = resp.xpath('/html/body/div/div[3]/div[3]/div[1]/div[1]/div/ul/li/div/div/div/div[1]/h3/a/@href').extract()for url in detail_url:# 对每个详细新闻链接发起请求yield scrapy.Request(url=url, callback=self.parse_detail_content)# 提取并处理新闻详细内容defparse_detail_content(self, resp,**kwargs):# 提取新闻标题
        title = resp.xpath('//*[@id="contain"]/div[2]/h1/text()').extract_first()# 提取新闻内容
        con = resp.xpath('//*[@id="content"]/div[2]//text()').extract()
        con =''.join(con).strip()
        data ={'title': title,'con': con}# 封装提取的数据print(data)# 打印数据yield data  # 返回提取的数据
使用场景

这种结合Selenium和Scrapy的方法适用于需要处理动态加载内容的网页,如新闻网站、社交媒体平台等。

结语

通过结合Selenium和Scrapy,我们可以有效地处理那些动态加载内容的网页,这对于数据抓取和网络爬虫项目至关重要。希望这篇文章能够帮助您在面对类似的挑战时,有所启发和帮助。


标签: selenium scrapy python

本文转载自: https://blog.csdn.net/weixin_39973810/article/details/134971391
版权归原作者 一勺菠萝丶 所有, 如有侵权,请联系我们删除。

“使用Selenium与Scrapy处理动态加载网页内容的解决方法”的评论:

还没有评论