【问题标题】:how to get a script value in html in 'response.text' using re.search?如何使用 re.search 在“response.text”中获取 html 中的脚本值?
【发布时间】:2021-10-31 21:41:14
【问题描述】:

我有一个 HTML 文件,该文件包含几个脚本,特别是在最后一个脚本中包含一个我想要获取的值

我需要得到这里找到的哈希值

extend(cur, { "hash": "13334a0e457f0793ec", "loginHost": "login", "sureBoxText": false, "strongCode": 0, "joinParams": false, "validationType": 3, "resendDelay": 120, "calledPhoneLen": 4, "calledPhoneExcludeCountries": [1, 49, 200] });

为此我使用了

import re

with open("test.html", "r", encoding='utf-8') as f:
    html = f.read()

hash = re.search(r'{ "hash": "(.*?)",', html).group(1)

完美运行,但是当我尝试直接从请求中执行相同操作时,出现错误。

with requests.get(url, headers=headers, cookies=cookies) as response:
        if response.status_code == 200:
            html = response.content
            hash = re.search(r'{ "hash": "(.*?)",', html).group(1)
            return hash

错误

TypeError: cannot use a string pattern on a bytes-like object

然后我执行了一个简单的测试,将“response.text”保存在一个 html 文件中并尝试以第一种方式读取,但错误仍然存​​在 在我输入文件并在我的 vscode 中单击以格式化文件后不久,它修复了整个 html 文件,我执行了测试并且它有效。 我需要一种将“response.text”格式化为 html 的方法,这样我就可以获得我的价值,或者如果有另一种我不知道我愿意学习的方法。

OBS 哈希值在'response.text'中找到

【问题讨论】:

    标签: python beautifulsoup python-requests python-re


    【解决方案1】:

    尝试使用str()html 转换为字符串:

    hash = re.search(r'{ "hash": "(.*?)",', str(html)).group(1)
    

    编辑:您的正则表达式不正确,将其更改为:

    hash = re.search(r'"hash":"(.*?)",', str(html)).group(1)
    

    【讨论】:

    • error AttributeError: 'NoneType' 对象没有属性 'group'
    • @DamiDoug 可能是正则表达式有问题,去掉str()会怎样,还能用吗?
    • 错误一直存在
    • @DamiDoug 所以问题出在正则表达式,因为它没有找到匹配项,它返回None,因此您收到错误,请考虑稍微调整正则表达式以正确找到匹配。网址是什么?
    • @DamiDoug 查看我的编辑
    【解决方案2】:

    您需要将字节解码为字符串:

    re.search(r'{ "hash": "(.*?)",', html.decode('utf-8'))
    

    【讨论】:

    • 错误:AttributeError:'str'对象没有属性'decode'。你的意思是:'编码'?
    • @DamiDoug 您的错误表明您有字节,因此您需要解码以获取字符串。 html的类型是什么?
    • 我不知道类型,我只是订购。我怎样才能看到类型
    • 你可以在你的函数中添加print(type(html))
    • 类型
    【解决方案3】:

    我相信您正在寻找response.text,它是“响应的内容,采用 unicode。”。见https://2.python-requests.org/en/master/api/#requests.Response.text

    with requests.get(url, headers=headers, cookies=cookies) as response:
            if response.status_code == 200:
                html = response.text
                hash = re.search(r'{ "hash": "(.*?)",', html).group(1)
                return hash
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-16
      • 1970-01-01
      • 2017-06-08
      • 2023-03-23
      • 1970-01-01
      • 1970-01-01
      • 2018-01-14
      • 2011-09-13
      相关资源
      最近更新 更多