小白学习使用 Python + Scrapy 爬取动态网页

Scrapy是什么?

一个主流的爬虫框架

怎么装?

pip install scrapy

对于python 3.4以上版本,请用

pip3 install scrapy

scrapy 框架会依赖一些其他框架,如安装过程提示缺少其他框架请自行安装

动态网页是什么?

按F12,Element 和 Source 不一致,Source这个静态页面是不完整的。我们需要爬取的内容在Soucre页面找不到

爬取动态网页主要有两种思路:

1. 找到数据文件,如*.json,直接爬取Json文件并解析里面想要的数据
2. 调用浏览器执行动态网页,待网页的动态加载完成后再像对静态网页那样进行爬取

使用selenium调用浏览器执行动态页面需安装:

pip install selenium
pip install chromedriver_installer

xpath 语法:

self.browser.find_elements_by_xpath 返回所有符合xpath的WebElements
任何一个WebElement都可以调用find_element(s)_by_xxx, 在xpath表达式中使用.约束在当前WebElement内查找

参考http://www.w3schools.com/xml/xpath_syntax.asp

《小白学习使用 Python + Scrapy 爬取动态网页》 xp.PNG

WebElement.text返回文本内容
WebElement.getattribute(href)获取attribute value

代码:

import time
from scrapy.spider import Spider
from selenium import webdriver

class LiCaiSpider(Spider):
    name = "LiCai"
    allowed_domains = ["haohaolicai.com"]
    start_urls = [
        "https://www.haohaolicai.com/page/borrow/period_profit.jsp?borrowWay=5"
#        "http://www.dmoz.org/Computers/Programming/Languages/Python/Resources/"
    ]

    def __init__(self)
        # use any browser you wish
        self.browser = webdriver.Chrome() #使用前请安装对应的webdriver
    

    def __del__(self):
        self.browser.close()

    def parse(self, response):
        #start browser
        self.browser.get(response.url)
        sampleSet = set()
        ItemList = self.browser.find_elements_by_xpath('//div[@class="period_model"]/ul')
        for item in ItemList:
            optText = item.find_element_by_xpath('.//li[@class="period_model_li6"]/a').text
            monText = item.find_element_by_xpath('.//li[@class="period_model_li4"]/span').text
            if( monText == '6' and optText =='立即投资'):
                sampleSet.add(item.find_element_by_xpath('.//li[@class="period_model_li1"]').text)
               
        filename = 'mycrapy'
        open(filename, 'w').write(repr(sampleSet))
点赞