【发布时间】:2021-12-26 16:56:51
【问题描述】:
以下代码完美运行,感谢@AKX
from pprint import pprint
sess = requests.Session()
# Do initial GET request, grab CSRF token
resp = sess.get("https://chartink.com/")
resp.raise_for_status()
csrf_token_m = re.search(r'<meta name="csrf-token" content="(.+?)" />', resp.text)
csrf_token = csrf_token_m.group(1)
# Do data query
resp = sess.post("https://chartink.com/screener/process",
data={"scan_clause":"( {cash} ( latest count( 90, 1 where latest ha-low > latest ichimoku cloud top( 9 , 26 , 52 ) ) = 90 ) )"},
headers={"Referer": "https://chartink.com/","x-csrf-token": csrf_token,"x-requested-with": "XMLHttpRequest"})
resp.raise_for_status()
data = resp.json()
pprint(data)
但是当我尝试使用 torpy 实现相同的功能时,我收到一条错误消息:“AttributeError: '_GeneratorContextManager' object has no attribute 'get'”,在此语句 resp = sess.get("https://chartink.com/")
req = TorRequests()
sess = req.get_session()
# Do initial GET request, grab CSRF token
resp = sess.get("https://chartink.com/")
resp.raise_for_status()
csrf_token_m = re.search(r'<meta name="csrf-token" content="(.+?)" />', resp.text)
csrf_token = csrf_token_m.group(1)
# Do data query
resp = sess.post("https://chartink.com/screener/process", data={"scan_clause": "( {cash} ( latest count( 90, 1 where latest ha-low > latest ichimoku cloud top( 9 , 26 , 52 ) ) = 90 ) )"},
headers={"Referer": "https://chartink.com/", "x-csrf-token": csrf_token,
"x-requested-with": "XMLHttpRequest"})
resp.raise_for_status()
pprint(resp.json())
有什么想法吗?谢谢
@AKX 根据您的建议,我更改了代码并使用了 with 语句,它起作用了。但是我无法理解它是如何与“with”一起工作的,并且可以在没有“with”语句的情况下编写代码吗?
这里是修改后的代码:
with TorRequests() as req:
with req.get_session() as sess:
# Do initial GET request, grab CSRF token
resp = sess.get("https://chartink.com/")
resp.raise_for_status()
csrf_token_m = re.search(r'<meta name="csrf-token" content="(.+?)" />', resp.text)
csrf_token = csrf_token_m.group(1)
# Do data query
resp = sess.post("https://chartink.com/screener/process", data={"scan_clause": "( {cash} ( latest count( 90, 1 where latest ha-low > latest ichimoku cloud top( 9 , 26 , 52 ) ) = 90 ) )"},
headers={"Referer": "https://chartink.com/", "x-csrf-token": csrf_token,
"x-requested-with": "XMLHttpRequest"})
resp.raise_for_status()
pprint(resp.json())
【问题讨论】:
-
您正在使用的特定库是什么?
-
是,torpy.
-
嗯,答案很简单,您需要使用 with 语句来使用库提供的会话。
-
根据您的建议,我更改了代码并使用了 with 语句,它起作用了。但是我无法理解它如何与“with”一起使用,并且可以在没有“with”语句的情况下编写代码吗?
标签: python python-3.x tor