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 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297
| from bs4 import BeautifulSoup from bs4.element import Comment import requests, json, random, time, urllib, re
class province: def __init__(self, province_name, city_list = None): self.province_name = province_name if not city_list : self.city_list = [] else: self.city_list = city_list
def parseJSON(dct): if isinstance(dct, dict): p = province(str(dct["province_name"]), dct["city_list"]) return p return dct
class city: def __init__(self, city, href, searchUrl = '', detailUrl = None): self.city = city self.href = href self.searchUrl = searchUrl if not detailUrl : self.detailUrl = [] else: self.detailUrl = detailUrl
def parseJSON(dct): if isinstance(dct, dict): p = city(str(dct["city"]), str(dct["href"]), str(dct["searchUrl"]), dct["detailUrl"]) return p return dct
class urlContext: def __init__(self, urlName, href, text = '', content = '') -> None: self.urlName = urlName self.href = href self.text = text self.content = content
def parseJSON(dct): if isinstance(dct, dict): p = urlContext(str(dct["urlName"]), str(dct["href"]), str(dct["text"]), str(dct["content"])) return p return dct
class download(object): def __init__(self): self.server = 'http://www.bendibao.com/' self.target = 'http://www.bendibao.com/index.htm' self.search = 'http://sou.%s.bendibao.com/cse/search' self.search_question = "人才落户" self.proxies = { "http": None, "https": None} self.headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:88.0) Gecko/20100101 Firefox/88.0', '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', 'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6,zh-TW;q=0.5', 'Connection' : 'close' } self.provinces = [] def get_search_url(self) : for p in self.provinces : if isinstance(p, province) : for c in p.city_list : if isinstance(c, city) : try: tmp_html = requests.get(url = c.href, headers = self.headers, proxies = self.proxies, timeout = 5) except requests.exceptions.ConnectionError as connError: message = "An exception of type {0} occurred.".format(type(connError).__name__) print(message) continue except requests.exceptions.RequestException as reqExcep: message = "An exception of type {0} occurred. ".format(type(reqExcep).__name__) print(message) continue tmp_html.encoding = 'UTF-8' body_bf = BeautifulSoup(tmp_html.text, "html.parser") try: input = body_bf.find('input', attrs={'name': "s", 'type': "hidden"}) s_value = input.get('value') if(s_value == ''): continue tmpurl = body_bf.select('div.search_nav > form') url_value = tmpurl[0].get('action') except Exception as excep: message = "An exception of type {0} occurred. Arguments:\n{1!r}".format(type(excep).__name__, excep.args) print(message) continue params = { "s" : s_value, "q" : self.search_question } str_params = urllib.parse.urlencode((params)) final_url = url_value + "?" + str_params c.searchUrl = final_url print(c.searchUrl) time.sleep(random.uniform(0.1, 0.2)) def get_detail_url(self) : for p in self.provinces: if isinstance(p, province): for c in p.city_list : if isinstance(c, city) and c.searchUrl != "": try: tmp_html = requests.get(url = c.searchUrl, headers = self.headers, proxies = self.proxies, timeout = 5) except requests.exceptions.ConnectionError as connError: message = "An exception of type {0} occurred.".format(type(connError).__name__) print(message) continue except requests.exceptions.RequestException as reqExcep: message = "An exception of type {0} occurred. ".format(type(reqExcep).__name__) print(message) continue tmp_html.encoding = 'UTF-8' body_bf = BeautifulSoup(tmp_html.text, "html.parser") try: tmpurl = body_bf.select('div.result.f.s0 > h3 > a') for u in tmpurl: print(u) du = u.get('href') print(str(u.get_text())) ds = str(u.get_text()).replace('<em>','').replace('</em>','') ds = re.sub('- [\u4e00-\u9fa5]*本地宝$', '', ds) tmp_detailUrl = urlContext(ds, du) c.detailUrl.append(tmp_detailUrl) except Exception as excep: message = "An exception of type {0} occurred. Arguments:\n{1!r}".format(type(excep).__name__, excep.args) print(message) continue time.sleep(random.uniform(0.1, 0.2))
def get_download_url(self): req = requests.get(url = self.target, headers = self.headers, proxies = self.proxies, timeout = 5) req.encoding = 'UTF-8' html = req.text div_bf = BeautifulSoup(html, "html.parser") div = div_bf.findAll('div', class_ = 'city-list') dl_bf = BeautifulSoup(str(div[0]), "html.parser") dl = dl_bf.find_all('dl') for each_dl in dl: dt_bf = BeautifulSoup(str(each_dl), "html.parser") dt = dt_bf.find('dt') aProvince = province(str(dt.string)) a = dt_bf.findAll('a') for each_a in a: aCity = city(each_a.string, each_a.get('href')) aProvince.city_list.append(aCity) self.provinces.append(aProvince) def get_detail_content(self, city_name) : if isinstance(city_name, str) and city_name.upper == 'ALL': city_name = True for tmp_province in self.provinces: if isinstance(tmp_province, province): for tmp_city in tmp_province.city_list : if isinstance(tmp_city, city) and (tmp_city.city == city_name or city_name): for tmp_detail in tmp_city.detailUrl : if isinstance(tmp_detail, urlContext) : try: tmp_html = requests.get(url = tmp_detail.href, headers = self.headers, proxies = self.proxies, timeout = 5) except requests.exceptions.ConnectionError as connError: message = "An exception of type {0} occurred.".format(type(connError).__name__) print(message) continue except requests.exceptions.RequestException as reqExcep: message = "An exception of type {0} occurred. ".format(type(reqExcep).__name__) print(message) continue tmp_html.encoding = 'UTF-8' body_bf = BeautifulSoup(tmp_html.text, "html.parser") try : tmp_content = body_bf.select('div#bo.content') for tmp_element in tmp_content[0](text=lambda text: isinstance(text, Comment)): tmp_element.extract() for tmp_div in tmp_content[0].find_all("div"): tmp_div.decompose() for tmp_script in tmp_content[0].find_all('script'): tmp_script.decompose() for tmp_a in tmp_content[0].find_all('a'): tmp_a.decompose() for tmp_p_vci in tmp_content[0].find_all('p', class_='view_city_index'): tmp_p_vci.decompose() for tmp_span in tmp_content[0].find_all('span'): tmp_span.decompose() tmp_detail.text = str(tmp_content[0].get_text().strip()) list = str(tmp_content[0].contents) print(list ,"\n\n") tmp_detail.content = str(tmp_content[0].contents) except Exception as excep : message = "An exception of type {0} occurred. Arguments:\n{1!r}".format(type(excep).__name__, excep.args) print(message) continue time.sleep(random.uniform(0.1, 0.2)) def write_to_json(self, path): with open(path, 'w', encoding='utf-8') as f: json.dump(dict({'provinces': self.provinces}), f, indent=4, default=lambda obj: obj.__dict__, ensure_ascii=False ) def read_from_json(self, path): with open(path, 'r', encoding='utf-8') as f: data = json.load(f) if isinstance(data, dict) : self.provinces = data['provinces'] for i_province in range(len(self.provinces)): self.provinces[i_province] = province.parseJSON(self.provinces[i_province]) if isinstance(self.provinces[i_province], province): for i_city in range(len(self.provinces[i_province].city_list)): self.provinces[i_province].city_list[i_city] = city.parseJSON(self.provinces[i_province].city_list[i_city]) if isinstance(self.provinces[i_province].city_list[i_city], city): for i_detail in range(len(self.provinces[i_province].city_list[i_city].detailUrl)): self.provinces[i_province].city_list[i_city].detailUrl[i_detail] = urlContext.parseJSON(self.provinces[i_province].city_list[i_city].detailUrl[i_detail])
if __name__ == "__main__" : dl = download()
choice = input("1.get from web\n2.get from local json\nyour choice:") if choice == '1' : dl.get_download_url() dl.get_search_url() dl.get_detail_url() dl.get_detail_content("ALL") dl.write_to_json('./bendibao/data/provinces.json') elif choice == '2' : dl.read_from_json('./bendibao/data/provinces.json') dl.get_detail_content("ALL") dl.write_to_json('./bendibao/data/provinces.json') else : pass
|