【问题标题】:Extracting all text from a website using scrapy / cleaning up the data使用scrapy/清理数据从网站中提取所有文本
【发布时间】:2020-02-17 21:21:38
【问题描述】:

我一直在尝试创建一个程序(我将分享下面的代码),它将扫描它可以在域中找到的每个页面,然后抓取该站点上包含的所有文本。

我创建了一个程序,该程序似乎从每个页面中获取所有文本,但是所有信息在所有网站代码中都“丢失”并显示为这样。

n\t\t\t\t', '\n\t\t\t\t', '\n\t\t\t\t', '\n\t\t\t' , '干衬是一种用于覆盖建筑内表面的系统 gs,例如在不需要“湿”石膏时使用石膏板的墙壁和天花板。', '\t\t', '\n\t\t\t\t', '\n\t\t\t \t\t\t', '\n\t\t\t', '\n\t\t', '\n\t\t\t\t\t\t', '\n\t \t\t', '\n\ ', '\n\t\t\t\t\t\t', '\n\t\t\t', '\n\t\t', '\n\t\t\t\t ', '\n\t\t\t', '\n\t\t\t\t\t', '\n\t\t\t\t', '\n\t\t\t \t', '\n\t\t\t', 'Coving', '\t\t', '\n\t\t\t\t', '\n\ t\t\t\t', '\n\t\t\t\t', '\n\t\t\

谁能帮我清理一下文本,以便我只留下相关信息!

代码如下:

from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor


class MySpider(CrawlSpider):
    name = 'c'
    allowed_domains = ['billsplastering.co.uk']
    start_urls = ['https://www.billsplastering.co.uk/']

    rules = (
        Rule(LinkExtractor(), callback='parse_item', follow=True),
    )

    def parse_item(self, response):
        filename = response.url.split("/")[-2] + '.html'
        with open(filename, 'wb') as f:
            f.write(response.body)
        print(response.css("::text").extract())```




【问题讨论】:

  • 使用.strip() 去除包括制表符和换行符的前导和尾随空格
  • 这听起来可以解决问题,但我不确定将其放入代码的何处。请给我一个简单的例子可以吗:)

标签: python python-3.x web-scraping scrapy


【解决方案1】:

试试这个。它从您在代码上方发布的列表中删除前导和尾随空格。然后它过滤掉空字符串。

list_body = [
    'n\t\t\t\t', '\n\t\t\t\t', '\n\t\t\t\t', '\n\t\t\t', 
    'Dry lining is a system for cladding the internal faces of buildin gs, such as walls and ceilings when with plasterboard when "wet" plaster is not required.', 
    '\t\t', '\n\t\t\t\t', '\n\t\t\t\t\t\t', '\n\t\t\t', '\n\t\t', 
    '\n\t\t\t\t\t\t', '\n\t\t\t', '\n\ ', '\n\t\t\t\t\t\t', '\n\t\t\t', '\n\t\t', 
    '\n\t\t\t\t', '\n\t\t\t', '\n\t\t\t\t\t', '\n\t\t\t\t', '\n\t\t\t\t', 
    '\n\t\t\t', 'Coving', '\t\t', '\n\t\t\t\t', '\n\ t\t\t\t', '\n\t\t\t\t', '\n\t\t\t']

# Strip blanks from items in list
list_no_blanks = [text.strip() for text in list_body]

# Filter out empty strings
list_filter = list(filter(lambda x: x != "", list_no_blanks))

【讨论】:

  • 该代码清除了大约 99% 的模糊问题,这很棒!谢谢罗伯
猜你喜欢
  • 1970-01-01
  • 2014-06-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-30
  • 2018-01-09
相关资源
最近更新 更多