如何解决在旧的for循环中使用存储在旧for循环中的项目名称
我正在使用的该程序将搜索URL的多个路径(位于JSON列表中),并找到一个未被使用的路径(404页)。
问题=当我遇到404(当我可以找到错误div时),我想打印路径是什么。但是我找不到解决办法,因为项目名称似乎无法访问。
### Libraries ###
from bs4 import BeautifulSoup
import grequests
import requests
import json
import time
### User inputs ###
namelist = input('Your namelist: ')
print('---------------------------------------')
result = input('Output file: ')
print('---------------------------------------')
### Scrape ###
names = json.loads(open(namelist + '.json').read())
reqs = (grequests.get('https://steamcommunity.com/id/' + name) for name in names)
resp=grequests.imap(reqs,grequests.Pool(10))
for r in resp:
soup = BeautifulSoup(r.text,'lxml')
findelement = soup.find_all('div',attrs={'class':"error_ctn"})
if (findelement):
print(name)
else:
print('trying')
解决方法
我认为您可以通过修改for循环的位置来做到这一点。我对您所使用的库不熟悉,因此在可能需要进一步修改代码的地方留下了评论,但遵循以下要求的方法应该可以起作用:
names = json.loads(open(namelist + '.json').read())
for name in names:
req = grequests.get('https://steamcommunity.com/id/' + name)
# May need to modify this line since only passing one req,so are assured of only one response
resp=grequests.imap(req,grequests.Pool(10))
# There should only be one response now.
soup = BeautifulSoup(resp.text,'lxml')
findelement = soup.find_all('div',attrs={'class':"error_ctn"})
if (findelement):
print(name)
else:
print('trying')
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。