【问题标题】:Python web-scraping error - TypeError: can't use a string pattern on a bytes-like objectPython web-scraping 错误 - TypeError: can't use a string pattern on a bytes-like object
【发布时间】:2014-06-24 14:52:58
【问题描述】:

我想构建一个网络爬虫。目前,我正在学习 Python。这是最基本的!

Python 代码

import urllib.request
import re

htmlfile = urllib.request.urlopen("http://basketball.realgm.com/")

htmltext = htmlfile.read()
title = re.findall('<title>(.*)</title>', htmltext)

print (htmltext)

错误:

  File "C:\Python33\lib\re.py", line 201, in findall
    return _compile(pattern, flags).findall(string)
TypeError: can't use a string pattern on a bytes-like object

【问题讨论】:

    标签: python-3.x web-scraping scraper findall


    【解决方案1】:

    您必须对数据进行解码。由于有问题的网站说

    charset=iso-8859-1
    

    使用它。 utf-8 在这种情况下不起作用。

    htmltext = htmlfile.read().decode('iso-8859-1')
    

    【讨论】:

    • 这行得通,但我仍然很困惑为什么我们必须放置一个 decode('iso-8859-1')。是否有不需要添加的网站?
    • @Jtwa 检查您尝试抓取的站点的源代码以获取 charset=...。对于您问题中的站点,字符集是 iso-8859-1。如果没有给出,你最好的选择通常是 utf-8。
    【解决方案2】:

    使用字节文字作为模式:

    title = re.findall(b'<title>(.*)</title>', htmltext)
    

    或将检索到的数据解码为字符串:

    title = re.findall('<title>(.*)</title>', htmltext.decode('utf-8'))
    

    (使用适当的文档编码更改utf-8

    【讨论】:

      猜你喜欢
      • 2011-06-26
      • 1970-01-01
      • 2022-11-11
      • 1970-01-01
      • 2017-05-08
      • 2019-09-24
      • 1970-01-01
      • 2021-12-13
      • 1970-01-01
      相关资源
      最近更新 更多