鍍金池/ 問答/Java  Python  HTML/ 如何獲取最新的ua?

如何獲取最新的ua?

大家好,我的代碼是掉入坑里了?為什么每次循環(huán)5次都是相同的UA,我想五次獲取不同的UA,該如何寫?
user_agent 是一個(gè)ua的列表,從setting導(dǎo)入

from setting import user_agent
import random



reload(sys)
sys.setdefaultencoding('utf8')

def ua():
    return random.choice(user_agent)


header = {
    "Accept":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
    "Accept-Encoding":"gzip, deflate, br",
    "Accept-Language":"zh-CN,zh;q=0.9",
    "Connection":"keep-alive",
    "Upgrade-Insecure-Requests":"1",
    "User-Agent":ua()
}

for url in range(5):
    print header

代碼執(zhí)行結(jié)果:

{'Accept-Language': 'zh-CN,zh;q=0.9', 'Accept-Encoding': 'gzip, deflate, br', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8', 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_3) AppleWebKit/535.20 (KHTML, like Gecko) Chrome/19.0.1036.7 Safari/535.20', 'Connection': 'keep-alive', 'Upgrade-Insecure-Requests': '1'}
{'Accept-Language': 'zh-CN,zh;q=0.9', 'Accept-Encoding': 'gzip, deflate, br', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8', 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_3) AppleWebKit/535.20 (KHTML, like Gecko) Chrome/19.0.1036.7 Safari/535.20', 'Connection': 'keep-alive', 'Upgrade-Insecure-Requests': '1'}
{'Accept-Language': 'zh-CN,zh;q=0.9', 'Accept-Encoding': 'gzip, deflate, br', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8', 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_3) AppleWebKit/535.20 (KHTML, like Gecko) Chrome/19.0.1036.7 Safari/535.20', 'Connection': 'keep-alive', 'Upgrade-Insecure-Requests': '1'}
{'Accept-Language': 'zh-CN,zh;q=0.9', 'Accept-Encoding': 'gzip, deflate, br', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8', 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_3) AppleWebKit/535.20 (KHTML, like Gecko) Chrome/19.0.1036.7 Safari/535.20', 'Connection': 'keep-alive', 'Upgrade-Insecure-Requests': '1'}
{'Accept-Language': 'zh-CN,zh;q=0.9', 'Accept-Encoding': 'gzip, deflate, br', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8', 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_3) AppleWebKit/535.20 (KHTML, like Gecko) Chrome/19.0.1036.7 Safari/535.20', 'Connection': 'keep-alive', 'Upgrade-Insecure-Requests': '1'}

都是相同的ua,如何改,能改為不同的UA呢?在函數(shù)里

回答
編輯回答
解夏

你ua在字典中只調(diào)用了一次。
這樣就行了

for url in range(5):
    header["User-Agent"] = ua()
    print header
2018年8月9日 13:48