scrapy LinkExtractor 提取链接相关用法 crawl 模板

目录

不使用 crawl 模板创建好 LinkExtractor 

描述提取规则的参数

参数默认值

allow

deny

allow_domains

deny_domains

restrict_xpath 与 restrict_css

tags

attrs

process_value


使用 crawl 模板

rules = (

        # 所以可以得到提取的正则表达式为'.*?/n.*?shtml’

        Rule(LinkExtractor(allow=('.*?/n.*?shtml'), allow_domains=('sohu.com')), callback='parse_item', follow=True),

    )

 

不使用 crawl 模板创建好 LinkExtractor 

在 spider 中自己导入的示例,如果使用 crawl 模板,会创建 LinkEXtractor 规则,让你自己去补充

#提取下一页链接,使用 LinkExtractor 提取
        from scrapy.linkextractors import LinkExtractor
        
        le = LinkExtractor(restrict_css='ul.pager li.next')
        links = le.extract_links(response)
        if links:
            next_url = links[0].url
            yield scrapy.Request(next_url,callback=self.parse)
  • 导入 LinkEXtractor 模块
  • 创建一个对象,使用 css 描述提取链接的规则
  • 给这个对象的 extract_links 方法传入 response 对象,该方法依据描述规则提取链接,最终返回一个列表,其中每一个元素都是 Link 对象,即提取到的一个链接
  • 由于此页面中的洗衣液链接只有一个,因此用 links[0] 获取 Link 对象,Link 对象的 url 属性便是链接页面的绝对链接,无需调用 response.urljoin 方法

 

 

描述提取规则的参数

参数默认值

LinkExtractor 构造器所有参数都有默认值,如果不传参数,就提取页面中所有链接

from sccrapy.linkextractors import LinkExtractor

le = LinkExtractor()
links = le.extract_links(response) 

 

allow

接收一个正则表达式或一个正则表达式列表,,提取绝对链接与正则表达式匹配的链接,如果该参数为空(默认),就提取全部链接

from sccrapy.linkextractors import LinkExtractor

pat = '正则表达'
le = LinkExtractor(allow=pat)
links = le.extract_links(response) 

 

deny

接收一个正则表达式或一个正则表达式列表,排除与正则表达式匹配的链接

from sccrapy.linkextractors import LinkExtractor

pat = '正则表达'
le = LinkExtractor(allow=pat)
links = le.extract_links(response) 

 

allow_domains

接收一个域名或一个域名列表,提取指定域的链接,例如提取域名为 baidu.com 和 github.com 链接

from sccrapy.linkextractors import LinkExtractor

domains = ['baidu.com','github.com']
le = LinkExtractor(allow_domains=domains)
links = le.extract_links(response) 

 

deny_domains

接收一个域名或一个域名列表,排除指定域的链接,例如排除域名为 baidu.com 和 github.com 链接

from sccrapy.linkextractors import LinkExtractor

domains = ['baidu.com','github.com']
le = LinkExtractor(deny_domains=domains)
links = le.extract_links(response) 

 

restrict_xpath 与 restrict_css

使用 xpath 与 css 描述规则,例如用 css 获取 url

<ul class="pager">  
    <li class="current">
        Page 1 of 50
    </li>        
    <li class="next">
        <a href="catalogue/page-2.html">next</a>
    </li>
</ul>
le = LinkExtractor(restrict_css='ul.pager li.next')
links = le.extract_links(response)
if links:
    next_url = links[0].url !!!!!!在 li 标签属性为 next 中的 a 标签的属性对应的链接可以直
                                       接 .url

 

tags

接收一个标签(字符串)或一个标签列表,提取指定标签内的链接,默认为 ['a','area']

 

attrs

接收一个属性(字符串)或一个属性列表,提取指定属性内的链接,默认为 ['href'],例如提取 HTML 中引用 JavaScript 的链接

...
<head>
    <script type='text/javascript' src='/js/app1.js/>
    <script type='text/javascript' src='/js/app2.js/>
</head>
...
from sccrapy.linkextractors import LinkExtractor

le = LinkExtractor(tags='script',attrs='src')
links = le.extract_links(response) 

>>>
['http://xxx.com/js/app1.js',
 'http://xxx.com/js/app2.js']

 

process_value

接收一个回调函数,如果传了该参数,LinkExtractor 将调用该回调函数对提取的每一个链接(如 a 的 href)进行处理,回调函数正常情况下应返回一个字符串(处理结果)想要抛弃所处理的链接时,返回 None

import re
def process(value):
    m = re.search('正则',value)
    #如果匹配,就提取其中 url 并返回,不匹配这返回原值
    if m:
        value = m.group(1)
    return value

from scrapy.linkextractors import LinkExtractor

le = LinkExtractor(process_value=process)
links = le.extract_links(response)
    

 

首先,你需要安装Scrapy爬虫框架,如果你还没有安装,可以使用`pip install scrapy`命令。这里是一个简单的Scrapy爬虫示例,用于提取百度首页的新闻标题和链接,并将结果保存为CSV文件。假设你已经创建了一个名为`my_spider.py`的Python文件: ```python # my_spider.py import scrapy from scrapy.spiders import Rule from scrapy.linkextractors import LinkExtractor from itemadapter import ItemAdapter import csv class BaiduNewsSpider(scrapy.Spider): name = 'baidunews' start_urls = ['http://www.baidu.com'] def parse(self, response): # 使用LinkExtractor选取所有a标签(通常包含新闻链接) links_extractor = LinkExtractor(allow=(r'http://news.baidu.com/\d+/\w+', r'https?://news.baidu.com/\d+/\w+')) for href in links_extractor.extract_links(response): yield { 'title': '', 'href': href.url, # 获取新闻链接 } # 这里我们暂时无法获取标题,因为需要解析HTML才能找到 # 对于每个新闻链接,我们需要发送一个新的请求并处理结果 for link in response.css('div.news_item a::attr(href)').getall(): yield response.follow(link, self.parse_item) def parse_item(self, response): # 为了提取标题,我们需要解析HTML。这通常涉及CSS选择器或XPath。这里仅展示基本结构 title = response.css('h2.title::text').get() if title is not None: item = {'title': title, 'href': response.url} # 创建ItemAdapter将字典转换为Item对象 item_adapter = ItemAdapter(item) # 写入CSV文件 with open('news.csv', 'a', newline='', encoding='utf-8') as f: writer = csv.DictWriter(f, fieldnames=['title', 'href']) writer.writerow(item_adapter.get()) # 如果响应中有更多的链接,继续提取 for next_link in response.css('.next a::attr(href)').getall(): yield response.follow(next_link, self.parse_item) # 遍历下一页直到没有更多内容 # 启动爬虫之前记得设置该项目的LOG级别,例如:scrapy crawl baidunews -o news.csv -t csv ``` 这个例子没有完全实现新闻标题的抓取,因为Scrapy默认的BeautifulSoup解析器并不能很好地解析动态加载的内容,如JavaScript渲染的新闻列表。如果网页是静态的,你可以尝试使用上述CSS选择器来定位标题元素。对于动态内容,你可能需要使用如Selenium这样的工具配合。 注意运行前需要确保网站允许爬虫访问,并遵守其robots.txt规则。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值