我正在制作一个脚本,但它的一部分存在一些问题,所以我将只粘贴该部分而不是所有脚本。无论如何,这只有一部分也可以单独使用。在这里:
import re, random, os.path, urllib.request
from bs4 import BeautifulSoup
def proxyget():
if os.path.isfile("proxy.txt"):
out_file = open("proxy.txt","w")
out_file.write("")
out_file.close()
else:
pass
url = "https://www.inforge.net/xi/forums/liste-proxy.1118/"
soup = BeautifulSoup(urllib.request.urlopen(url), "lxml")
base = "https://www.inforge.net/xi/"
for tag in soup.find_all("a", {"class":"PreviewTooltip"}):
links = tag.get("href")
final = base + links
result = urllib.request.urlopen(final)
for line in result :
ip = re.findall("(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3}):(?:[\d]{1,5})", str(line))
if ip:
print("Proxy grabbed=> "+'\n'.join(ip))
for x in ip:
out_file = open("proxy.txt","a")
while True:
out_file.write(x+"\n")
out_file.close()
break
def withproxy():
try:
out_file = str(input("Enter the proxy list: "))
with open(out_file) as x:
proxylist = list(x)
for y in proxylist:
proxylist = y.split('\n')
proxy = random.choice(proxylist).split(':')
except:
print ("Error to read file, try again")
withproxy()
host = proxy[0]
port = int(proxy[1])
proxyget()
withproxy()
我不明白为什么有时这部分代码可以运行,有时会显示此错误:
Proxy grabbed=> x.x.x.x:x
Enter the proxy list: proxy.txt
Traceback (most recent call last):
File "proxytry.py", line 44, in <module>
withproxy()
File "proxytry.py", line 41, in withproxy
port = int(proxy[1])
IndexError: list index out of range
这有什么问题吗?你能帮帮我吗?
请您参考如下方法:
proxylist = y.split('\n')
在列表末尾创建一个空字符串 '' 使得 proxylist = [..., '']。
因此,当 random.choice 选择列表中的一项时,在某个时候它会选择 '' ,为此 split ':' 返回包含一项 [''] 的列表。
proxy[1] 因此将引发 IndexError。
我也不明白为什么在使用引用 proxylist 迭代列表时在循环中使用名称 proxylist:
for y in proxylist:
proxylist = y.split('\n') # avoid ambuguity, use another name
很遗憾,我无法为您的代码生成工作版本,因为我不知道您正在读取的文件的确切内容。我认为最好不要猜测。
