Python大数据之从网页上爬取数据的方法详解
作者:xuehyunyu 发布时间:2023-10-06 22:10:53
标签:Python,大数据,网页,爬取数据
本文实例讲述了Python大数据之从网页上爬取数据的方法。分享给大家供大家参考,具体如下:
myspider.py :
#!/usr/bin/python
# -*- coding:utf-8 -*-
from scrapy.spiders import Spider
from lxml import etree
from jredu.items import JreduItem
class JreduSpider(Spider):
name = 'tt' #爬虫的名字,必须的,唯一的
allowed_domains = ['sohu.com']
start_urls = [
'http://www.sohu.com'
]
def parse(self, response):
content = response.body.decode('utf-8')
dom = etree.HTML(content)
for ul in dom.xpath("//div[@class='focus-news-box']/div[@class='list16']/ul"):
lis = ul.xpath("./li")
for li in lis:
item = JreduItem() #定义对象
if ul.index(li) == 0:
strong = li.xpath("./a/strong/text()")
li.xpath("./a/@href")
item['title']= strong[0]
item['href'] = li.xpath("./a/@href")[0]
else:
la = li.xpath("./a[last()]/text()")
item['title'] = la[0]
item['href'] = li.xpath("./a[last()]/href")[0]
yield item
items.py :
# -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/items.html
import scrapy
class JreduItem(scrapy.Item):#相当于Java里的实体类
# define the fields for your item here like:
# name = scrapy.Field()
title = scrapy.Field()#创建一个field对象
href = scrapy.Field()
pass
middlewares.py :
# -*- coding: utf-8 -*-
# Define here the models for your spider middleware
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/spider-middleware.html
from scrapy import signals
class JreduSpiderMiddleware(object):
# Not all methods need to be defined. If a method is not defined,
# scrapy acts as if the spider middleware does not modify the
# passed objects.
@classmethod
def from_crawler(cls, crawler):
# This method is used by Scrapy to create your spiders.
s = cls()
crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
return s
def process_spider_input(self, response, spider):
# Called for each response that goes through the spider
# middleware and into the spider.
# Should return None or raise an exception.
return None
def process_spider_output(self, response, result, spider):
# Called with the results returned from the Spider, after
# it has processed the response.
# Must return an iterable of Request, dict or Item objects.
for i in result:
yield i
def process_spider_exception(self, response, exception, spider):
# Called when a spider or process_spider_input() method
# (from other spider middleware) raises an exception.
# Should return either None or an iterable of Response, dict
# or Item objects.
pass
def process_start_requests(self, start_requests, spider):
# Called with the start requests of the spider, and works
# similarly to the process_spider_output() method, except
# that it doesn't have a response associated.
# Must return only requests (not items).
for r in start_requests:
yield r
def spider_opened(self, spider):
spider.logger.info('Spider opened: %s' % spider.name)
pipelines.py :
# -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
import codecs
import json
class JreduPipeline(object):
def __init__(self):
self.fill = codecs.open("data.txt",encoding="utf-8",mode="wb");
def process_item(self, item, spider):
line = json.dumps(dict(item))+"\n"
self.fill.write(line)
return item
settings.py :
# -*- coding: utf-8 -*-
# Scrapy settings for jredu project
#
# For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation:
#
# http://doc.scrapy.org/en/latest/topics/settings.html
# http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html
# http://scrapy.readthedocs.org/en/latest/topics/spider-middleware.html
BOT_NAME = 'jredu'
SPIDER_MODULES = ['jredu.spiders']
NEWSPIDER_MODULE = 'jredu.spiders'
# Crawl responsibly by identifying yourself (and your website) on the user-agent
#USER_AGENT = 'jredu (+http://www.yourdomain.com)'
# Obey robots.txt rules
ROBOTSTXT_OBEY = True
# Configure maximum concurrent requests performed by Scrapy (default: 16)
#CONCURRENT_REQUESTS = 32
# Configure a delay for requests for the same website (default: 0)
# See http://scrapy.readthedocs.org/en/latest/topics/settings.html#download-delay
# See also autothrottle settings and docs
#DOWNLOAD_DELAY = 3
# The download delay setting will honor only one of:
#CONCURRENT_REQUESTS_PER_DOMAIN = 16
#CONCURRENT_REQUESTS_PER_IP = 16
# Disable cookies (enabled by default)
#COOKIES_ENABLED = False
# Disable Telnet Console (enabled by default)
#TELNETCONSOLE_ENABLED = False
# Override the default request headers:
#DEFAULT_REQUEST_HEADERS = {
# 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
# 'Accept-Language': 'en',
#}
# Enable or disable spider middlewares
# See http://scrapy.readthedocs.org/en/latest/topics/spider-middleware.html
#SPIDER_MIDDLEWARES = {
# 'jredu.middlewares.JreduSpiderMiddleware': 543,
#}
# Enable or disable downloader middlewares
# See http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html
#DOWNLOADER_MIDDLEWARES = {
# 'jredu.middlewares.MyCustomDownloaderMiddleware': 543,
#}
# Enable or disable extensions
# See http://scrapy.readthedocs.org/en/latest/topics/extensions.html
#EXTENSIONS = {
# 'scrapy.extensions.telnet.TelnetConsole': None,
#}
# Configure item pipelines
# See http://scrapy.readthedocs.org/en/latest/topics/item-pipeline.html
ITEM_PIPELINES = {
'jredu.pipelines.JreduPipeline': 300,
}
# Enable and configure the AutoThrottle extension (disabled by default)
# See http://doc.scrapy.org/en/latest/topics/autothrottle.html
#AUTOTHROTTLE_ENABLED = True
# The initial download delay
#AUTOTHROTTLE_START_DELAY = 5
# The maximum download delay to be set in case of high latencies
#AUTOTHROTTLE_MAX_DELAY = 60
# The average number of requests Scrapy should be sending in parallel to
# each remote server
#AUTOTHROTTLE_TARGET_CONCURRENCY = 1.0
# Enable showing throttling stats for every response received:
#AUTOTHROTTLE_DEBUG = False
# Enable and configure HTTP caching (disabled by default)
# See http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html#httpcache-middleware-settings
#HTTPCACHE_ENABLED = True
#HTTPCACHE_EXPIRATION_SECS = 0
#HTTPCACHE_DIR = 'httpcache'
#HTTPCACHE_IGNORE_HTTP_CODES = []
#HTTPCACHE_STORAGE = 'scrapy.extensions.httpcache.FilesystemCacheStorage'
最后需要一个程序入口的方法:
main.py :
#!/usr/bin/python
# -*- coding:utf-8 -*-
#爬虫文件的执行入口
from scrapy import cmdline
cmdline.execute("scrapy crawl tt".split())
希望本文所述对大家Python程序设计有所帮助。
来源:https://blog.csdn.net/xuehyunyu/article/details/74562406


猜你喜欢
- 在使用SQL Server存储过程或者触发器时,通常会使用自定义异常来处理一些特殊逻辑。例如游标的销毁,事务的回滚。接下来将会详细的介绍SQ
- 下学期就要学习MySQL了,没事先在家搞一搞,没想到光安装就费了半天劲,所以我决定整理下,供大家参考。第一步 下载安装包:官网毕竟是甲骨文公
- 在 Python 中,函数可以通过以下语法定义和使用:def function_name(parameter1, parameter2, .
- 安装:pip install wave在wav 模块中 ,主要介绍一种方法:getparams(),该方法返回的结果如下:_wave_par
- 目录01 — Pytest核心功能02 — 创建测试项目03 — 编写测试用例04 — 执行测试用例05 — 数据与脚本分离06 — 参数化
- #测试网址: http://localhost/blog/testurl.php?id=5 //获取域名或主机地址 echo $_SERVE
- 今天遇到这个问题,上网查到以下解决方法:1.检查你的磁盘剩余空间是否足够,如果没有磁盘剩余空间,则清理磁盘,腾出空间
- 本文实例讲述了python用来获得图片exif信息的库用法。分享给大家供大家参考。具体分析如下:exif-py是一个纯python实现的获取
- python爬取淘宝商品销量的程序,运行程序,输入想要爬取的商品关键词,在代码中的‘###'可以进一步约束商品的属性,比如某某作者的
- 有些使用Z-Blog的用户询问我,怎么实现我的月光博客首页上这种自动图文混排的版式效果,今天我就详细介绍一下在Z-Blog中实现这种图文混排
- 基本思路就是,使用MIMEMultipart来标示这个邮件是多个部分组成的,然后attach各个部分。如果是附件,则add_header加入
- 在vue中使用ant-design-vue组件官方地址:Ant Design Vue1. 安装首先使用vue-cli创建项目,然后进入项目,
- 前言本文主要给大家介绍关于python中__init__、__new__和__call__方法的相关内容,分享出来供大家参考学习,下面话不多
- 1. 确认已经安装了NT/2000和SQL Server的最新补丁程序,不用说大家应该已经安装好了,但是我觉得最好还是在这里提醒一下。2.
- 函数没有SQL的可移植性强 能运行在多个系统上的代码称为可移植的(portable)。相对来说,多数SQL语句是可移植的,在SQL实现之间有
- 什么是迭代器能被 next 指针调用,并不断返回下一个值的对象,叫做迭代器。表示为Iterator,迭代器是一个对象类型数据。概念迭代器指的
- 这边我是需要得到图片在Vgg的5个block里relu后的Feature Map (其余网络只需要替换就可以了)索引可以这样获得vgg =
- 熟悉 C 语言的小伙伴一定对 goto 语句不陌生,它可以在代码之间随意的跳来跳去,但是好多老鸟都告诫大家,不要使用 goto,因为 got
- 很早之前就在PJ的blog上看到可以用VS2005调试ASP程序,但是没有写出具体的步骤,后来一次偶尔也让我找到了方法,但是一直没把它写出来
- 直接上图,图文并茂,相信你很快就知道要干什么。A文件:B文件:可以发现,A文件中“汉字井号”这一列和B文件中“WELL”这一列的属性相同,以