爬虫之爬取网页数据

###环境:Anaconda2虚拟环境

  • 步骤1

打开Anaconda Prompt命令行窗口,输入conda activate tfenv激活虚拟环境,进入所要创建爬虫项目的文件夹,比如说我在F:\hadoop\python-project目录下创建爬虫项目。输入scrapy startproject firstspider创建firstspider项目

python爬取网页中的表格 python爬取网络表格数据_python

  • 步骤2
    在pycharm中打开刚新建的项目,目录结构如图所示
    spiders:这里面写爬虫程序
    items:写实体( python类)
    middlewares:中间件( 修改代理、使用IP池等)
    pipelines:管道,写存储数据的代码
    settings:配置爬虫的行为

选择编译器,在这里我选的是虚拟环境下的编译器

python爬取网页中的表格 python爬取网络表格数据_python_02

  • 步骤3
    判断所要爬取的网站是否可爬,在Anaconda Prompt 的项目下,输入scrapy view https://bj.lianjia.com/ershoufang/,这里我用的是链家网的网址。当命令运行结束后,就会在浏览器端打开链家网,如图所示
  • python爬取网页中的表格 python爬取网络表格数据_虚拟环境_03

  • 地址栏显示在本地C盘,这表示该网站可爬。
    scrapy view可以将网页下载到本地,这个网页就是爬虫看到的页面。注意:爬虫看到的页面与直接到目标网站看到的页面有些是不相同的,因为有反爬虫处理。
  • 步骤4,确定要抓取的内容
    首先使用scrapy shell https://bj.lianjia.com/ershoufang/命令,调试所要抓取的内容
  • python爬取网页中的表格 python爬取网络表格数据_python 爬虫_04

  • 返回200,打开链家网页
  • python爬取网页中的表格 python爬取网络表格数据_虚拟环境_05

  • 选取你要爬取的内容,比如说我要爬取房屋的标题,用xpath选择器
  • python爬取网页中的表格 python爬取网络表格数据_python爬取网页中的表格_06

response.xpath('//*[@id="content"]/div[1]/ul/li[1]/div[1]/div[1]/a/text()').extract_first()

python爬取网页中的表格 python爬取网络表格数据_虚拟环境_07


可以看到,我们要的内容已经获取到了。

  • 步骤5写爬虫程序
    1、在spider目录下的example.py文件中,编写爬虫程序,如下:
import scrapy

from firstspider.items import FirstspiderItem

class ExampleSpider(scrapy.Spider):
    name = 'example'                        #爬虫程序名,可自己取
    allowed_domains = ['bj.lianjia.com']      #爬取网站的域名
    start_urls = ['https://bj.lianjia.com/ershoufang/']  #爬取的网站

    def parse(self, response):
        housename = response.xpath('//*[@id="content"]/div[1]/ul/li[1]/div[1]/div[1]/a/text()').extract_first()
        price = response.xpath('//*[@id="content"]/div[1]/ul/li[1]/div[1]/div[6]/div[1]/span/text()').extract_first()
        item = FirstspiderItem()            #创建一个Item实例
        item["housename"] = housename
        item["price"] = price
        return item

2、在items.py文件中写python实体类,如下:

import scrapy

class FirstspiderItem(scrapy.Item):
    # define the fields for your item here like:
    # name = scrapy.Field()
    housename = scrapy.Field()
    price = scrapy.Field()

3、设置管道,写存储数据的代码,如下:

class FirstspiderPipeline(object):
    def process_item(self, item, spider):
        with open("house.txt", "a") as f:
                content="{},{}\n".format(item["housename"],item["price"])
                f.write(content)

4、启用配置,在settings.py文件中,设置ROBOTSTXT_OBEY = False

python爬取网页中的表格 python爬取网络表格数据_python爬取网页中的表格_08


和启用管道,将注释去掉,如下:

python爬取网页中的表格 python爬取网络表格数据_python 爬虫_09


5、运行爬虫程序,命令为scrapy crawl example,可以在命令行窗口下运行,也可在pycharm中运行。如下是在pycharm中的项目终端下运行的

python爬取网页中的表格 python爬取网络表格数据_ide_10


运行完成后,可看到项目目录下多了一个house.txt文件,如图:

python爬取网页中的表格 python爬取网络表格数据_python爬取网页中的表格_11


至此,简单的爬虫就完成了。