【问题标题】:Scrapy extract table from website网站上的 Scrapy 提取表
【发布时间】:2023-03-18 01:27:02
【问题描述】:

我是一名 Python 新手,正在尝试编写一个脚本来从 page 中提取数据。使用scrapy,我写了如下代码:

import scrapy

class dairySpider(scrapy.Spider):
    name = "dairy_price"

    def start_requests(self):
        urls = [
            'http://www.dairy.com/market-prices/?page=quote&sym=DAH15&mode=i',

        ]
        for url in urls:
            yield scrapy.Request(url=url, callback=self.parse)




    def parse(self, response):
        for rows in response.xpath("//tr"):
            yield {
                'text': rows.xpath(".//td/text()").extract().strip('. \n'),

                }

但是,这并没有刮掉任何东西。你有什么想法 ? 谢谢

【问题讨论】:

    标签: python html web-scraping scrapy


    【解决方案1】:

    通过向http://shared.websol.barchart.com/quotes/quote.php?page=quote&sym=DAH15&mode=i&domain=blimling&display_ice=&enabled_ice_exchanges=&tz=0&ed=0 发出请求,页面http://www.dairy.com/market-prices/?page=quote&sym=DAH15&mode=i 上的表格被动态添加到DOM

    您应该废弃第二个链接而不是第一个链接。因为scrapy.Request只会返回html源代码,不会返回使用javascript添加的内容。

    更新

    这是提取表格数据的工作代码

    import scrapy
    
    class dairySpider(scrapy.Spider):
        name = "dairy_price"
    
        def start_requests(self):
            urls = [
                "http://shared.websol.barchart.com/quotes/quote.php?page=quote&sym=DAH15&mode=i&domain=blimling&display_ice=&enabled_ice_exchanges=&tz=0&ed=0",
            ]
    
            for url in urls:
                yield scrapy.Request(url=url, callback=self.parse)
    
    
        def parse(self, response):
            for row in response.css(".bcQuoteTable tbody tr"):
                print row.xpath("td//text()").extract()
    

    确保编辑您的settings.py 文件并将ROBOTSTXT_OBEY = True 更改为ROBOTSTXT_OBEY = False

    【讨论】:

    • 谢谢,我用第二个链接替换了 URL。但是刮板不起作用,表格上的数据没有被刮掉。我的 xpath 不正确,如何为我的行选择好的 xpath?
    • 我尝试使用第二个链接,问题是第二个链接上的 robots.txt 文件不允许scrapy 工作。要解决此问题,请将 settings.py 中的 ROBOTSTXT_OBEY = True 更改为 ROBOTSTXT_OBEY = False。
    • 这至少可以确保您从网站获得响应并且您的解析回调函数将被调用。
    • 我更新了答案以帮助您进行表格提取。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-09
    • 2020-10-12
    相关资源
    最近更新 更多