Scrapy - 从表中提取项目

2023-11-27

试图了解 Scrapy,但遇到了一些死胡同。

我在一页上有 2 个表,想从每个表中提取数据,然后移至下一页。

表看起来像这样(第一个称为 Y1,第二个称为 Y2)并且结构相同。

<div id="Y1" style="margin-bottom: 0px; margin-top: 15px;">
                                <h2>First information</h2><hr style="margin-top: 5px; margin-bottom: 10px;">                    

                <table class="table table-striped table-hover table-curved">
                    <thead>
                        <tr>
                            <th class="tCol1" style="padding: 10px;">First Col Head</th>
                            <th class="tCol2" style="padding: 10px;">Second Col Head</th>
                            <th class="tCol3" style="padding: 10px;">Third Col Head</th>
                        </tr>
                    </thead>
                    <tbody>

                        <tr>
                            <td>Info 1</td>
                            <td>Monday 5 September, 2016</td>
                            <td>Friday 21 October, 2016</td>
                        </tr>
                        <tr class="vevent">
                            <td class="summary"><b>Info 2</b></td>
                            <td class="dtstart" timestamp="1477094400"><b></b></td>
                            <td class="dtend" timestamp="1477785600">
                            <b>Sunday 30 October, 2016</b></td>
                        </tr>
                        <tr>
                            <td>Info 3</td>
                            <td>Monday 31 October, 2016</td>
                            <td>Tuesday 20 December, 2016</td>
                        </tr>


                    <tr class="vevent">
                        <td class="summary"><b>Info 4</b></td>                      
                        <td class="dtstart" timestamp="1482278400"><b>Wednesday 21 December, 2016</b></td>
                        <td class="dtend" timestamp="1483315200">
                        <b>Monday 2 January, 2017</b></td>
                    </tr>



                </tbody>
            </table>

正如你所看到的,结构有点不一致,但只要我能得到每个 td 并输出到 csv 那么我就会很高兴。

我尝试使用 xPath 但这只会让我更加困惑。

我的最后一次尝试:

import scrapy

class myScraperSpider(scrapy.Spider):
name = "myScraper"

allowed_domains = ["mysite.co.uk"]
start_urls =    (
                'https://mysite.co.uk/page1/',
                )

def parse_products(self, response):
    products = response.xpath('//*[@id="Y1"]/table')
    # ignore the table header row
    for product in products[1:]  
       item = Schooldates1Item()
       item['hol'] = product.xpath('//*[@id="Y1"]/table/tbody/tr[1]/td[1]').extract()[0]
       item['first'] = product.xpath('//*[@id="Y1"]/table/tbody/tr[1]/td[2]').extract()[0]
       item['last'] = product.xpath('//*[@id="Y1"]/table/tbody/tr[1]/td[3]').extract()[0]
       yield item

这里没有错误,但它只是返回大量有关爬网的信息,但没有实际结果。

Update:

  import scrapy

       class SchoolSpider(scrapy.Spider):
name = "school"

allowed_domains = ["termdates.co.uk"]
start_urls =    (
                'https://termdates.co.uk/school-holidays-16-19-abingdon/',
                )

  def parse_products(self, response):
  products = sel.xpath('//*[@id="Year1"]/table//tr')
 for p in products[1:]:
  item = dict()
  item['hol'] = p.xpath('td[1]/text()').extract_first()
  item['first'] = p.xpath('td[1]/text()').extract_first()
  item['last'] = p.xpath('td[1]/text()').extract_first()
  yield item

这给我:IndentationError:意外缩进

如果我运行下面修改后的脚本(感谢@Granitosaurus)以输出到 CSV (-o schoolDates.csv),我会得到一个空文件:

import scrapy

class SchoolSpider(scrapy.Spider):
name = "school"
allowed_domains = ["termdates.co.uk"]
start_urls = ('https://termdates.co.uk/school-holidays-16-19-abingdon/',)

def parse_products(self, response):
    products = sel.xpath('//*[@id="Year1"]/table//tr')
    for p in products[1:]:
        item = dict()
        item['hol'] = p.xpath('td[1]/text()').extract_first()
        item['first'] = p.xpath('td[1]/text()').extract_first()
        item['last'] = p.xpath('td[1]/text()').extract_first()
        yield item

这是日志:

  • 2017-03-23 12:04:08 [scrapy.core.engine] 信息:蜘蛛打开 2017-03-23 12:04:08 [scrapy.extensions.logstats] 信息:已爬网 0 页数 (0 页/分钟), 刮掉 0 条 (0 条/分钟) 2017-03-23 12:04:08 [scrapy.extensions.telnet] 调试:Telnet 控制台监听 于... 2017-03-23 12:04:08 [scrapy.core.engine] 调试:爬行(200) https://termdates.co.uk/robots.txt>(参考:无)2017-03-23 12:04:08 [scrapy.core.engine] 调试:爬行 (200) https://termdates.co.uk/school-holidays-16-19-abingdon/> (参考: 无)2017-03-23 12:04:08 [scrapy.core.scraper]错误:蜘蛛错误 处理 https://termdates.co.uk/school-holidays-16-19-abingdon/> (参考: 没有任何)回溯(最近一次调用最后一次):文件 “c:\python27\lib\site-packages\twisted\internet\defer.py”,第 653 行, 在_runCallbacks中 current.result = 回调(current.result, *args, **kw) 文件 "c:\python27\lib\site-packages\scrapy-1.3.3-py2.7.egg\scrapy\spiders__init__.py", 第 76 行,解析中 raise NotImplementedError NotImplementedError 2017-03-23 12:04:08 [scrapy.core.engine] INFO:关闭蜘蛛(已完成)2017-03-23 12:04:08 [scrapy.statscollectors] 信息:转储 Scrapy 统计数据: {'下载者/request_bytes':467,'下载者/request_count':2, '下载器/request_method_count/GET':2, '下载器/response_bytes':11311,'下载器/response_count':2, 'downloader/response_status_count/200': 2, 'finish_reason': '完成', 'finish_time': datetime.datetime(2017, 3, 23, 12, 4, 8, 845000), 'log_count/DEBUG': 3, 'log_count/ERROR': 1, 'log_count/INFO': 7, 'response_received_count': 2, '调度程序/出队':1,'调度程序/出队/内存':1, '调度程序/排队': 1, '调度程序/排队/内存': 1, 'spider_exceptions/NotImplementedError':1,'start_time': datetime.datetime(2017, 3, 23, 12, 4, 8, 356000)} 2017-03-23 12:04:08 [scrapy.core.engine] INFO: Spider 已关闭(已完成)

Update 2:(跳过行) 这会将结果推送到 csv 文件,但会跳过每隔一行。

外壳显示{'hol':无,'最后':u'\r\n\t\t\t\t\t\t\t\t','第一个':无}

import scrapy

class SchoolSpider(scrapy.Spider):
name = "school"
allowed_domains = ["termdates.co.uk"]
start_urls = ('https://termdates.co.uk/school-holidays-16-19-abingdon/',)

def parse(self, response):
    products = response.xpath('//*[@id="Year1"]/table//tr')
    for p in products[1:]:
        item = dict()
        item['hol'] = p.xpath('td[1]/text()').extract_first()
        item['first'] = p.xpath('td[2]/text()').extract_first()
        item['last'] = p.xpath('td[3]/text()').extract_first()
        yield item

Solution: 谢谢 @vold这会抓取start_urls中的所有页面并处理不一致的表布局

# -*- coding: utf-8 -*-
import scrapy
from SchoolDates_1.items import Schooldates1Item

class SchoolSpider(scrapy.Spider):
name = "school"
allowed_domains = ["termdates.co.uk"]
start_urls = ('https://termdates.co.uk/school-holidays-16-19-abingdon/',
              'https://termdates.co.uk/school-holidays-3-dimensions',)

def parse(self, response):
    products = response.xpath('//*[@id="Year1"]/table//tr')
    # ignore the table header row
    for product in products[1:]:
        item = Schooldates1Item()
        item['hol'] = product.xpath('td[1]//text()').extract_first()
        item['first'] = product.xpath('td[2]//text()').extract_first()
        item['last'] = ''.join(product.xpath('td[3]//text()').extract()).strip()
        item['url'] = response.url
        yield item

您需要稍微更正您的代码。由于您已经选择了表中的所有元素,因此无需再次指向表。因此你可以将你的 xpath 缩短为这样的td[1]//text().

def parse_products(self, response):
    products = response.xpath('//*[@id="Year1"]/table//tr')
    # ignore the table header row
    for product in products[1:]  
       item = Schooldates1Item()
       item['hol'] = product.xpath('td[1]//text()').extract_first()
       item['first'] = product.xpath('td[2]//text()').extract_first()
       item['last'] = product.xpath('td[3]//text()').extract_first()
       yield item

编辑了我的答案,因为 @stutray 提供了网站的链接。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Scrapy - 从表中提取项目 的相关文章

  • HtmlAgilityPack - 获取文档中的所有节点

    我想使用 HtmlAgilityPack 遍历文档中的所有节点 将要 foreach HtmlNode node in myhtml DocumentNode SelectNodes do 你可以循环遍历myhtml DocumentNod
  • Scrapy 仅抓取每个页面的第一个结果

    我目前正在尝试运行以下代码 但它只保留每个页面的第一个结果 知道可能是什么问题吗 from scrapy contrib spiders import CrawlSpider Rule from scrapy contrib linkext
  • 从部分 XPath 获取完整 XPath

    我正在使用 selenium 和 perl 并在页面上有标签 要访问此标签 我有以下 xpath text some here 需要获取该元素的完整 xpath 的问题 例如 html body table tr any other and
  • 如何从下面的html中提取数据?

    我想要从中提取数据的 Html 是 div class infoMessageInner p span class ng binding Fiber r best lld till adressen Tj nsterna kan du be
  • Selenium 与 scrapy 的动态页面

    我正在尝试使用 scrapy 从网页中抓取产品信息 我要抓取的网页如下所示 从包含 10 个产品的 Product list 页面开始 单击 下一步 按钮将加载接下来的 10 个产品 两个页面之间的 URL 不会改变 我使用 LinkExt
  • 加快网络抓取速度

    我正在使用一个非常简单的网络抓取工具抓取 23770 个网页scrapy 我对 scrapy 甚至 python 都很陌生 但设法编写了一个可以完成这项工作的蜘蛛 然而 它确实很慢 爬行 23770 个页面大约需要 28 小时 我看过scr
  • 如何使用XPath选择非空段落?

    我想要抓取的网页具有类似的结构 每个都有一个段落是一个问题 一个段落是一个答案 我想抓取每个问题和答案并将它们存储在两个项目中 问题是 在某些页面上 问题和答案分别是 xxx p 1 and xxx p 2 但在其他页面上 xxx p 1
  • Scrapy:AttributeError:“列表”对象没有属性“iteritems”

    这是我关于堆栈溢出的第一个问题 最近想用linkedin 刮刀 https github com junks linkedInScraper 所以我下载并指示 scrapycrawl linkedin com 并收到以下错误消息 供您参考
  • libxmljs 的替代品 [关闭]

    Closed 此问题正在寻求书籍 工具 软件库等的推荐 不满足堆栈溢出指南 help closed questions 目前不接受答案 目标 使用 Node js 访问网页 使用 xpath 语法操作 DOM 并打印新的 DOM libxm
  • Python Scrapy:allowed_domains从数据库添加新域

    我需要向 allowed domains 添加更多域 因此我没有收到 已过滤的异地请求 我的应用程序获取从数据库获取的网址 因此我无法手动添加它们 我试图覆盖蜘蛛init 像这样 def init self super CrawlSpide
  • scrapy LinkExtractors 最终会得到唯一的链接吗?

    所以 我有一个包含很多文章和页码的页面 现在 如果我想提取一篇文章 我会使用 Rule LinkExtractor allow article html callback parse article 对于页面我使用这个规则 规则 LinkE
  • 如何使用 selenium 和 Mocha 获取 xPath() 选择的锚标记的文本

    我已经成功选择了 a 标签 我想显示锚标记的文本 但无法这样做 我正在使用 selenium mocha javascript 和 phantomJS 这是我的脚本 详细 var assert require assert var test
  • Scrapy Spider不存储状态(持久状态)

    您好 有一个基本的蜘蛛 可以运行以获取给定域上的所有链接 我想确保它保持其状态 以便它可以从离开的位置恢复 我已按照给定的网址进行操作http doc scrapy org en latest topics jobs html http d
  • 如何更新 PHP 中 xpath 的版本? [复制]

    这个问题在这里已经有答案了 可能的重复 XPath 2 0 和 或 XSLT 2 0 是否会在 PHP 中实现 https stackoverflow com questions 2085632 will xpath 2 0 and or
  • 我的扩展中未收到 Scrapy Spider_idle 信号

    我在几个蜘蛛之间有共同的行为spider idle正在接收信号 我想将此行为移至扩展中 我的分机已经监听spider opened and spider closed信号成功 但是 那spider idle未收到信号 这是我的扩展 为简洁起
  • 用于从链接中选择文本的 xpath 表达式

    我有这样的html文件内容 a class bf title Link to book href book 229920 book name a 帮我构造 xpath 表达式来获取链接文本 书名 我尝试使用 a 但表达式计算时没有结果 如果
  • XPath 将元素中的所有文本作为一个值获取,删除换行符

    我试图获取以下一组节点中的所有文本并作为一个值返回 而不是多个节点 p I love eating out br br This is my favorite restaurant br I will definitely be back
  • 如何添加剧作家的等待时间

    我正在将 scrapy 与 playwright 集成 但发现自己在单击后添加计时器时遇到困难 因此 当我点击后截取页面的屏幕截图时 它仍然挂在登录页面上 如何集成计时器以便页面等待几秒钟直到页面加载 选择器 onetrust close
  • xpath+ 正则表达式:匹配文本

    我正在尝试编写一个 xpath 以便仅返回包含文本和数字的节点 我想使用正则表达式并希望这能起作用 td matches text d 谁能帮我理解我在这里做错了什么 tr td 1 td td 10 td td a td tr 你缺少量化
  • 避免由于相对 URL 导致的错误请求

    我正在尝试使用Scrapy抓取一个网站 并且我想要抓取的每个页面的url都是使用这种相对路径编写的 a href en item to scrap html Link a 现在 在我的浏览器中 这些链接可以工作 您可以访问类似的网址http

随机推荐