Python爬虫框架Scrapy的基本使用方法(以爬取加密货币GitHub链接为例)

昨天有这个需求,其实之前从来没用过Scrapy,简单花2个小时学习了一下使用方法,估计也有很多朋友和我有同样的需求,这里就总结一些我的经验。

安装之类的就不说了,通过pip即可。上手也很简单,看看官网教程的也写得很明白:

https://docs.scrapy.org/en/latest/intro/overview.html

唯一需要注意的一点是,实际上我们在使用爬虫的时候,相比正则表达式(Regular Expression),更常用XPath,估计很多朋友对XPath并不熟悉,我用一个例子说明一下:

例如我想在这样一个网页中:https://coinmarketcap.com/all/views/all/,获取所有加密货币的GitHub链接。注意到每种加密货币页面中,GitHub链接以这种形式存在(以Bitcoin为例):

<li><span class="glyphicon glyphicon-hdd text-gray" title="Source Code"></span> <a href="https://github.com/bitcoin/" target="_blank" rel="noopener">Source Code</a></li>

在爬虫中,我们就需要唯一地匹配到这里面的链接,其实匹配的方法很简单,先把代码放出来:

for each in response.xpath('//li/a[starts-with(@href,"https://github.com/")]/@href'):

XPath中几种重要的标签解释如下:

1) // 双斜杠 定位根节点,会对全文进行扫描,在文档中选取所有符合条件的内容,以列表的形式返回。 
2) / 单斜杠 寻找当前标签路径的下一层路径标签或者对当前路标签内容进行操作 
3) /text() 获取当前路径下的文本内容 
4) /@xxxx 提取当前路径下标签的属性值 
5) | 可选符 使用|可选取若干个路径 如//p | //div 即在当前路径下选取所有符合条件的p标签和div标签。 

6) . 点 用来选取当前节点  7) .. 双点 选取当前节点的父节点 

所以,我们首先通过//li定位到这一行,然后href前面的标签a,然后用starts-with方法提取以https://github.com/内容开头的href标签,匹配到了之后再取href的属性值即可。

其他的内容大家一看便知,关于XPath的详细解释,可以看看这里:https://blog.csdn.net/winterto1990/article/details/47903653

最后给出完整的示例代码:

import scrapy
from scrapy.selector import Selector

class CoinSpider(scrapy.Spider):
    name="coin"
    allowed_domains=["coinmarketcap.com"]
    start_urls = [
        'https://coinmarketcap.com/all/views/all/',
    ]
    
    def parse(self,response):
                
        for each in response.xpath('//li/a[starts-with(@href,"https://github.com/")]/@href'):
            github_url=each.extract()
            print github_url

        for each in response.xpath('//a/@href'):
            suburl=each.extract()
            if(suburl.startswith('/currencies/')):
                yield scrapy.Request('https://coinmarketcap.com'+suburl, self.parse)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
# -*- coding:utf-8 -*- import sys #print (u'系统默认编码为',sys.getdefaultencoding()) default_encoding = 'utf-8' #重新设置编码方式为uft-8 if sys.getdefaultencoding() != default_encoding: reload(sys) sys.setdefaultencoding(default_encoding) #print (u'系统默认编码为',sys.getdefaultencoding()) import requests from bs4 import BeautifulSoup import traceback import re import xlwt def getURLDATA(url): #url = 'http://www.cnnvd.org.cn/web/xxk/ldxqById.tag?CNNVD=CNNVD-201901-1014' header={ 'user-agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.80 Safari/537.36', 'Connection': 'keep-alive',} r=requests.get(url,headers=header,timeout=30) #r.raise_for_status()抛出异常 html = BeautifulSoup(r.content.decode(),'html.parser') link=html.find(class_='detail_xq w770')#漏洞信息详情 link_introduce=html.find(class_='d_ldjj')#漏洞简介 link_others=html.find_all(class_='d_ldjj m_t_20')#其他 #print(len(link_introduce)) try: #print ("危害等级:"+link.contents[3].contents[3].find('a').text.lstrip().rstrip())#危害等级 list4.append(str(link.contents[3].contents[3].find('a').text.lstrip().rstrip())) except: #print("危害等级:is empty") list4.append("") try: #print ("CVE编号:"+link.contents[3].contents[5].find('a').text.lstrip().rstrip())#CVE编号 list5.append(str(link.contents[3].contents[5].find('a').text.lstrip().rstrip())) except: #print("CVE编号:is empty") list5.append("") try: #print ("漏洞类型:"+link.contents[3].contents[7].find('a').text.lstrip().rstrip())#漏洞类型 list6.append(str(link.contents[3].contents[7].find('a').text.lstrip().rstrip())) except : #print("漏洞类型:is empty") list6.append("") try: #print ("发布时间:"+link.contents[3].contents[9].find('a').text.lstrip().rstrip())#发布时间 list7.append(str(link.contents[3].contents[9].find('a').text.lstrip().rstrip())) except : #print("发布时间:is empty") list7.append("") try: #print ("威胁类型:"+link.contents[3].contents[11].find('a').text.lstrip().rstrip())#威胁类型 list8.append(str(link.contents[3].contents[11].find('a').text.lstrip().rstrip())) except : #print("威胁类型:is empty") list8.append("") try: #print ("更新时间:"+link.contents[3].contents[13].find('a').text.lstrip().rstrip())#更新时间 list9.append(str(link.contents[3].contents[13].find('a').text.lstrip().rstrip())) except : #print("更新时间:is empty") list9.append("") try: #print ("厂商:"+link.contents[3].contents[15].find('a').text.lstrip().rstrip())#厂商 list10.append(str(link.contents[3].contents[15].find('a').text.lstrip().rstrip())) except: #print("厂商:is empty") list10.append("") #link_introduce=html.find(class_='d_ldjj')#漏洞简介 try: link_introduce_data=BeautifulSoup(link_introduce.decode(),'html.parser').find_all(name='p') s="" for i in range(0,len(link_introduce_data)): ##print (link_introduce_data[i].text.lstrip().rstrip()) s=s+str(link_introduce_data[i].text.lstrip().rstrip()) #print(s) list11.append(s) except : list11.append("") if(len(link_others)!=0): #link_others=html.find_all(class_='d_ldjj m_t_20') #print(len(link_others)) try: #漏洞公告 link_others_data1=BeautifulSoup(link_others[0].decode(),'html.parser').find_all(name='p') s="" for i in range(0,len(link_others_data1)): ##print (link_others_data1[i].text.lstrip().rstrip()) s=s+str(link_others_data1[i].text.lstrip().rstrip()) #print(s) list12.append(s) except: list12.append("") try: #参考网址 link_others_data2=BeautifulSoup(link_others[1].decode(),'html.parser').find_all(name='p') s="" for i in range(0,len(link_others_data2)): ##print (link_others_data2[i].text.lstrip().rstrip()) s=s+str(link_others_data2[i].text.lstrip().rstrip()) #print(s) list13.append(s) except: list13.append("") try: #受影响实体 link_others_data3=BeautifulSoup(link_others[2].decode(),'html.parser').find_all('a',attrs={'class':'a_title2'}) s="" for i in range(0,len(link_others_data3)): ##print (link_others_data3[i].text.lstrip().rstrip()) s=s+str(link_others_data3[i].text.lstrip().rstrip()) #print(s) list14.append(s) except: list14.append("") try: #补丁 link_others_data3=BeautifulSoup(link_others[3].decode(),'html.parser').find_all('a',attrs={'class':'a_title2'}) s="" for i in range(0,len(link_others_data3)): ##print (link_others_data3[i].t

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值