1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175
|
import os import requests from lxml import html import time import re
''' 遇到网站远程关闭,自动重启3次,失败后需手动重启,不再retry,避免被ban
'''
headers = { 'Host': 'm.gsmarena.com', 'Accept-Language': 'en-US,en;q=0.9,ko;q=0.8', 'Accept-Encoding': 'gzip, deflate, br', 'Connection': 'keep-alive', 'Pragma': 'no-cache', 'Cache-Control': 'no-cache', 'Upgrade-Insecure-Requests': '1', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.80 Safari/537.36 Edg/98.0.1108.43', }
cookie = {} with open('./cookie.txt', 'r') as f: raw_cookies = f.read()
for line in raw_cookies.split(';'): key,value = line.split("=", 1) cookie[key] = value
proxies = { }
def save(text, filename='temp', path='download'): fpath = os.path.join(path, filename) if not os.path.exists(path): os.mkdir(path) with open(fpath, 'wb') as f: print('output:', fpath) f.write(text)
def requrlstotree(url): resp = requests.get(url, headers=headers) if not resp.status_code == requests.codes.ok: print('something wrong') print(url) return -1 time.sleep(5) page = resp.content tree = html.fromstring(page) return tree
def requrlstocont(url): resp = requests.get(url, headers=headers) print(resp.status_code) if not resp.status_code == requests.codes.ok: print('something wrong') print(url) return -1 time.sleep(5) page = resp.content return page
def savelog(text): with open('./log.txt', 'a') as f: f.write(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) + ': ' + text + '\n') print('log added')
def crawlurls(): url = 'https://www.gsmarena.com/makers.php3' tree = requrlstotree(url) if tree == -1: return -1 brands = tree.xpath('//tr//a/text()') print('total brands = ' + str(len(brands))) urls = tree.xpath('//tr//a/@href') print('total urls = ' + str(len(urls))) brandsurls = {} for i in range(len(brands)): urlsfull = 'https://' + headers['Host'] + '/' + urls[i] brandsurls[brands[i]] = urlsfull print(brands[i] + ' ' + urlsfull) models = [] for url in brandsurls.values(): tree = requrlstotree(url) if tree == -1: return -1 modelsPages = tree.xpath('//div[@class="nav-pages"]//a/@href') modelsPages = ['https://' + headers['Host'] + '/' + i for i in modelsPages] modelsPages.insert(0, url) print(modelsPages) for url in modelsPages: tree = requrlstotree(url) if tree == -1: return -1 urls = tree.xpath('//div[@class="makers"]//li/a/@href') urls = ['https://' + headers['Host'] + '/' + i for i in urls] models.extend(urls) print(models) save('\n'.join(models), 'all_models_urls.txt', './')
def crawlcontents(): print('filter exists files...') with open('./all_models_urls.txt', 'r') as f: modelsurlslist = f.readlines() modelslistall = [i.split('/')[-1] for i in modelsurlslist] modelslistall = [i.replace('\n', '') for i in modelslistall] print('modelslist ' + str(len(modelslistall))) modelslistexists = os.listdir('./pages/') print('modelslistexists ' + str(len(modelslistexists))) modelslistdiff = list(set(modelslistall).difference(set(modelslistexists))) modelslistdiff.sort() print('modelslistdiff ' + str(len(modelslistdiff))) print('special: ' + str(len(modelslistall) - len(modelslistexists) - len(modelslistdiff)))
for modelsfilename in modelslistdiff: global count if re.sub('[\/:*?"<>|]', '_', modelsfilename) in modelslistexists: print('special char: ' + modelsfilename) else: url = 'https://' + headers['Host'] + '/' + modelsfilename print(url) page = requrlstocont(url) if page == -1: return -1 filename = re.sub('[\/:*?"<>|]', '_', modelsfilename) save(page, filename,'./pages/')
count = 0 return 0
if __name__ == '__main__': flag = 1 count = 0 while(flag == 1): try: flag = crawlcontents() except: count += 1 print('try again') savelog('try again') time.sleep(60) if count > 2: print('tried 3 times') savelog('tried 3 times') break else: if flag == -1: savelog('something wrong') print('something wrong') break else: savelog('all done') print('all done') break
|