|
|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 要学习 于 2020-2-4 15:22 编辑
在测试一个国外站点的页面数据时,
时不时会遇上网络相应超时无法爬取到数据。
自己手动单页面爬取测试,发现没响应,停止运行代码,重新执行代码后,又能正常爬取了。
所以,想实现这样的效果:
当async with session.get(url, headers=headers, timeout=1, verify_ssl=False) as r:读取页面没响应时,程序又重新读取1次,
也就是一共读取两次,
这个代码要如何写呢
- async with session.get(url, headers=headers, timeout=1, verify_ssl=False) as r:
- html = await r.read()
复制代码
这样写?
- async def get_title(url):
- async with sem:
- # async with是异步上下文管理器
- async with aiohttp.ClientSession() as session: # 获取session
- trytimes = 2 # 重试的次数
- for i in range(trytimes):
- try:
- async with session.request('GET', url, verify=False, timeout=2) as resp:
- if requests.exceptions.Timeout:
- async with session.request('GET', url, verify=False, timeout=2) as resp:
复制代码
在网上找到的例子,但不知道如何修改
import requests
import time
def monirequest(isget=1, url='', header='', data='', i=1):
try:
if isget == 1:
response = requests.get(url, headers=header, timeout=0.5)
else:
response = requests.post(url, headers=header, data=data, timeout=1)
response.encoding = response.apparent_encoding
if response.status_code == 200:
return response.text
except requests.exceptions.Timeout:
if i == 1:
print('请求超时,第%s次重复请求' % i)
time.sleep(2)
if i == 2:
print('请求超时,第%s次重复请求' % i)
time.sleep(5)
if i == 3:
print('请求超时,第%s次重复请求' % i)
time.sleep(8)
if i > 4:
print('超时退出')
return 1
i += 1
monirequest(isget, url, header, data, i)
return -1
if __name__ == '__main__':
result = monirequest(1, "http://www.baidu.com/")
print(result) |
|