【问题标题】:How to convert CSS selected field into normal python string如何将 CSS 选定字段转换为普通的 python 字符串
【发布时间】:2020-05-27 20:39:19
【问题描述】:

当我使用 CSS 选择器时,我的 scrapy 项目给了我一个奇怪的项目编码。

相关代码如下:

一旦发出scrapy请求并下载网页,就会调用parse_page并返回响应......

    def parse_page(self, response):

        # Using Selenium WebDriver to select elements
        records = self.driver.find_elements_by_css_selector('#searchResultsTable > tbody > tr')

        for record in records:

            # Convert selenium object into scrapy.Selector object (necessary to use .add_css methods)  
            sel = Selector(text=record.get_attribute('outerHTML'))

            # Instantiate RecordLoader (a custom item loader)
            il = RecordLoader(item=Record(), selector=sel)

            # Select element and pass to example_field's input processor
            il.add_css('example_field', 'td:nth-child(2) > a::text')

il.add_css() 将 CSS 选择器的结果传递给 example_field 的输入处理器,用于演示目的只是打印语句并显示问题...

def example_field_input_processor(text_html):
    print(text_html)
    print(type(text_html))
    print(text_html.encode('utf-8'))

输出:

'\xa0\xa004/29/2020 10:50:24 AM,\xa0\xa0\xa0'

<class 'str'>

b'\xc2\xa0\xc2\xa004/29/2020 10:50:24 AM,\xc2\xa0\xc2\xa0\xc2\xa0'

这是我的问题:

1) 为什么 CSS 选择器不只是给我一个普通的 Python 字符串?是否与使用::text 将CSS 选择器转换为文本有关。是因为网页的编码不同吗?我检查了是否有指定网站编码的<meta> 标签,但没有。

2) 当我强制对“utf-8”进行编码时,为什么我得不到一个普通的 python 字符串而不是一个显示所有 Unicode 字符的字节字符串?

3) 我的目标是只有一个可以解析的普通 python 字符串(没有前置 b,没有奇怪的字符)。怎么样?

【问题讨论】:

    标签: python css web-scraping unicode scrapy


    【解决方案1】:

    在抓取时,您有时必须从 unicode 字符中清除结果

    它们通常是spaces tabs 的结果,有时是span

    通常的做法是清理你抓取的所有文本:

    def string_cleaner(rouge_text):
        return ("".join(rouge_text.strip()).encode('ascii', 'ignore').decode("utf-8"))
    

    说明:

    使用split()join 转换字符并清除它的unicodes。

    这部分代码"".join(rouge_text.strip())

    然后将其编码为ascii并解码为utf-8以去除特殊字符

    这部分代码.encode('ascii','ignore').decode("utf-8"))

    如何在代码中应用它

    print(string_cleaner(text_html))

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-18
      相关资源
      最近更新 更多