就是爬虫文件的类,可以通过 spider.xxx 调用属性或者方法
中间件 process_response() 中 selenium 加载动态数据替换非动态加载数据
# 下载器返回结果是替换响应结果
def process_response(self, request, response, spider):
url = response.url
print(url)
# 对 url 进行判断
if url in spider.joke_url_list:
driver = webdriver.Firefox()
driver.get(url)
driver.implicitly_wait(10)
while 1:
if not is_element_exists(driver, '//h1[@class="article-title"]'):
sleep(1)
continue
# 获取页面源码数据
web_page = driver.page_source
sleep(1.5)
driver.quit()
return HtmlResponse( # from scrapy.http import HtmlResponse
url=url, # 返回 url
body=web_page, # 替换响应数据
encoding='utf-8', # 设置编码
request=request # 返回 request
)
return response
scrapy startproject xxxPro
scrapy genspider -t crawl getUrl www.xxx.com
scrapy genspider -t crawl getUrl www.xxx.com
# -*- coding: utf-8 -*-
import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
class GeturlSpider(CrawlSpider):
name = 'getUrl'
# allowed_domains = ['www.xxx.com']
start_urls = ['http://www.qiushibaike.com/']
"""
# 正则匹配
# 直接匹配连接文本内容
"""
link_1 = LinkExtractor(allow=r'/8hr/page/\d+')
"""
# xpath 路径匹配
# 注意不需要 ./@href !!
"""
link_2 = LinkExtractor(restrict_xpaths='//ul[@class="pagination"]/li/a')
"""
# 可以添加多个匹配规则
# callback : 指定回调函数
# follow : False --> 只解析当前起始页符合规则的链接
# follow : True --> 在当前页提取出的连接中递归解析出缝合规则的链接
# 相同连接将会自动去重
"""
rules = (
Rule(link_1, callback='parse_item', follow=True),
Rule(link_2, callback='parse_item', follow=True),
)
def parse_item(self, response):
print(response)
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有