WildBloom

导航

 

网站地址:http://www.17500.cn/p5/all.php


 1、新建爬虫项目

scrapy startproject pfive

2、在spiders目录下新建爬虫

scrapy genspider pfive_spider www.17500.cn

3、在爬虫文件中修改入口url

start_urls = ['http://www.17500.cn/p5/all.php']

4、添加爬取条目

class PfiveItem(scrapy.Item):
    #开奖期号
    awardID = scrapy.Field()
    #开奖日期
    awardDate = scrapy.Field()
    #开奖号码
    awardNum = scrapy.Field()

5、编写爬虫,通过xpath解析网站

class PfiveSpiderSpider(scrapy.Spider):
    name = 'pfive_spider'
    allowed_domains = ['www.17500.cn']
    start_urls = ['http://www.17500.cn/p5/all.php']

    def parse(self, response):
        list = response.xpath("//table/tbody/tr/td/table/tbody/tr[3]/td[@class='normal']/table/tbody/tr[@bgcolor='#ffffff']")
        for l in list:
            pfiveItem = PfiveItem()
            pfiveItem['awardID'] = l.xpath('./td[1]/text()').extract_first()
            pfiveItem['awardDate'] = l.xpath('./td[2]/text()').extract_first()
            pfiveItem['awardNum'] = l.xpath('./td[3]/text()').extract_first()
            yield pfiveItem

6、在配置文件中忽略robots.txt文件(仅学习用)

# Obey robots.txt rules
ROBOTSTXT_OBEY = False

7、在配置文件中打开User_Agent

USER_AGENT = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36'

8、编写启动文件main.py

from scrapy import cmdline
cmdline.execute('scrapy crawl pfive_spider'.split())

 按理说这样就可以了,但是却抓不到东西!!!


通过查看response.text,发现表格数据是异步加载的,百度如何处理这种网页

https://blog.csdn.net/dangsh_/article/details/78633566

这个博主通过使用selenium 自动化测试包解决了这个问题。

9、首先编写下载中间件,并在配置中添加

class JavaScriptMiddleware(object):

    def process_request(self, request, spider):
        if spider.name == "pfive_spider":
            driver = webdriver.Chrome("G:\\Crawler\chromedriver.exe") #指定使用的浏览器
            driver.get(request.url)
            time.sleep(1)
            js = "var q=document.documentElement.scrollTop=10000" #模拟浏览页面
            driver.execute_script(js) #可执行js,模仿用户操作。此处为将页面拉至最底端。
            time.sleep(3)
            body = driver.page_source
            print ("访问"+request.url)
            return HtmlResponse(driver.current_url, body=body, encoding='utf-8', request=request)
        else:
            return None

注意闭坑:chromedriver.exe的版本要和本机chrom浏览器的版本一致。

http://chromedriver.storage.googleapis.com/index.html

OK,到此为止,大功告成


 

不对,这还只是第一页的数据。。。等下补更 

posted on 2019-07-09 13:22  WildBloom  阅读(1053)  评论(0编辑  收藏  举报