通常我在请求中编码,因此我对 aiohttp 没有太多经验。但由于请求被阻塞,我必须使用 aiohttp。
那么我的代码在请求中的样子:
#Account gen code is here using requests
r = requests.get(product_link)
watch_link = soup(r.text, "html.parser").find("div", {"id": "vi-atl-lnk"}).a["href"]
r = requests.get(watch_link)
r = requests.get(watch_link)
所以它的作用是转到 Ebay 列表,然后使用 BS4 抓取该列表源代码中的观看链接。然后,它使用 GET 请求将该列表添加到监视列表中。添加到监视列表链接上必须有 2 个 GET 请求,否则实际上不会添加它。
嗯,这是在请求中,但现在我需要在 aiohttp 中编写它。我得到的最接近的是:
session = aiohttp.ClientSession()
async def main():
#Account gen code is here using aiohttp and session
async with session.get(product_link) as resp:
r = await resp.text()
watch_link = soup(r, "html.parser").find("div", {"id": "vi-atl-lnk"}).a["href"]
async with session.get(watch_link) as respp:
time.sleep(.1)
async with session.get(watch_link) as resp:
time.sleep(.1)
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
我尝试了这个,它为我运行,但它没有将该项目添加到监视列表中。上面的代码(没有显示,因为它与这个问题无关)运行完美并创建了帐户。但当涉及到观察列表位时,它就不起作用了。这可能是什么原因?
最佳答案
我尝试了很多次,最后发现cookies有问题。您需要将代码更改为aiohttp.ClientSession(headers=headers)
。顺便说一句,事实可能就在 cookies 中,其中将 ;
转换为 \073
Not
aiohttp.ClientSession(headers=headers,cookies=cookies)
这是我整理的代码。
import aiohttp
import asyncio
from bs4 import BeautifulSoup as soup
product_link = ""
cookies = {"Cookie":"_ga=GA1.2.808...."}
headers = {"Connection": "keep-alive"}
headers.update(cookies)
async def main():
#Account gen code is here using aiohttp and session
async with aiohttp.ClientSession(headers=headers) as sessions:
async with sessions.get(product_link) as resp:
r = await resp.text()
watch_link = soup(r, "lxml").find("div", {"id": "vi-atl-lnk"}).a.get("href")
print(watch_link)
async with sessions.get(watch_link) as resp:
pass
async with sessions.get(watch_link) as resp:
pass
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
关于python - 使用同一个ClientSession获取多个不同的url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53048654/