第一次发表csdn,后悔没有早些把以前犯的错误发表,主要这次太坑了,python编辑时一定要注意缩进对齐,我一开始把for循环写到方法里了
导致运行时一直啥也没有,从怀疑函数random到怀疑人生...在写ip代理池是同样问题,后来简单写了个有random的方法调用,终于意识到是for循环缩进在方法里就一直是在方法里循环,再调用也没用,太坑了。 运行结果 。篇幅过长,只截取部分。
import urllib.request
import re
import random
uapools = [
"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:69.0) Gecko/20100101 Firefox/69.0",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.79 Safari/537.36 Edge/14.14393",
]
def ua(uapools):
thisua=random.choice(uapools)
print(thisua)
headers = ("User-Agent", thisua)
opener = urllib.request.build_opener()
opener.addheaders = [headers]
urllib.request.install_opener(opener)
for i in range(0, 10):
ua(uapools)
print(1)
thisurl = "http://www.lovehhy.net/Joke/Detail/QSBK/" + str(i + 1)
data = urllib.request.urlopen(thisurl).read().decode("GBK", "ignore")
pat = '</a></h3><div id="endtext"> (.*?)<br /><br /><br /></div>'
rst = re.compile(pat, re.S).findall(data)
for j in range(0, len(rst)):
thisrst = rst[j]
print(thisrst)
print("---------")