kygschp 发表于 2021-7-14 22:33:48

代理ip

求助,下面的代码为啥会出错啊,该怎么解决呢?

import urllib.request
import random

url = 'http://www.whatismyip.com.tw'

iplist = {'14.18.109.42:8081', '51.68.206.76:999','103.102.216.22:80','47.107.128.69:888','103.102.216.22:80'}
proxy = urllib.request.ProxyHandler({'http':random.choice(iplist)})
opener = urllib.request.build_opener(proxy)
response = opener.open(url)
content = response.read().decode('utf-8')
print(content)






---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-24-c56829fcea2b> in <module>
      2
      3 iplist = {'14.18.109.42:8081', '51.68.206.76:999','103.102.216.22:80','47.107.128.69:888','103.102.216.22:80'}
----> 4 proxy = urllib.request.ProxyHandler({'http':random.choice(iplist)})
      5 opener = urllib.request.build_opener(proxy)
      6 response = opener.open(url)

~\anaconda3\lib\random.py in choice(self, seq)
    289         except ValueError:
    290             raise IndexError('Cannot choose from an empty sequence') from None
--> 291         return seq
    292
    293   def shuffle(self, x, random=None):

TypeError: 'set' object is not subscriptable

青出于蓝 发表于 2021-7-15 07:33:50

import urllib.request
import random

url = 'http://www.whatismyip.com.tw'

iplist = ['14.18.109.42:8081', '51.68.206.76:999','103.102.216.22:80','47.107.128.69:888','103.102.216.22:80']
proxy = urllib.request.ProxyHandler({'http':random.choice(iplist)})
opener = urllib.request.build_opener(proxy)
response = opener.open(url)
content = response.read().decode('utf-8')
print(content)

青出于蓝 发表于 2021-7-15 07:34:34

iplist应该是列表而不是集合,random的choice无法用于集合
欢迎追问
页: [1]
查看完整版本: 代理ip