TypeError:字符串对象不可调用 请求模块

-1 投票
3 回答
3989 浏览
提问于 2025-04-19 11:02

大家好,我刚开始接触requests模块,正在玩这个模块,想找到一个特定的响应文本,但似乎找不到。

我尝试用if语句来检查r.text,但好像没成功!

错误信息:

C:\Python34\python.exe "C:/Users/Shrekt/PycharmProjects/Python 3/untitleds/gg.py"
Traceback (most recent call last):
File "C:/Users/Shrekt/PycharmProjects/Python 3/untitleds/gg.py", line 12, in <module>
if r.text("You have") !=-1:
TypeError: 'str' object is not callable

import requests

with requests.session() as s:
login_data = dict(uu='Wowsxx', pp='blahpassword', sitem='LIMITEDQTY')

#cookie = s.cookies['']

s.post('http://lqs.aq.com/login-ajax.asp', data=login_data, headers={"Host": "lqs.aq.com", "User-Agent": "Mozilla/5.0 (Windows NT 6.2; WOW64; rv:31.0) Gecko/20100101 Firefox/31.0", "Referer": "http://lqs.aq.com/default.asp", "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"})

r = s.get('http://lqs.aq.com/limited.asp')

if r.text("You have") !=-1:
    print("found")

3 个回答

0

你可能在想的是内置的 string.find() 函数。

string.find(s, sub[, start[, end]])

这个函数会返回字符串 s 中,子字符串 sub 第一次出现的位置索引。也就是说,它会告诉你 sub 在 s[start:end] 这个范围内的最低索引。如果没有找到,就返回 -1。start 和 end 的默认值,以及负数的解释,和切片的用法是一样的。

在这种情况下,你需要把

if r.text("You have") !=-1: // note that text is a string not a function
    print("found")

改成:

if r.text.find("You have") !=-1: // note that text.find is a function not a string! :)
    print("found")

或者你可以用更符合 Python 风格、更易读的方式来写。

if "You have" in r.text:
    print("found")
0

看起来你的问题出在这一行 r.text 上。

如果你去看看这个 文档 的介绍部分,你会发现 r.text 是一个字符串。

你应该把这一行改成这样:

if "You have" in r.text:

0
if r.text("You have") !=-1:

这不是检查 r.text(一个字符串)是否包含或等于某个特定字符串的正确方法。

你需要这样做:

if "You have" in r.text:  # Check for substring

或者

if r.text == "You have":  # Check for equality

撰写回答