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
| import requests import openpyxl from bs4 import BeautifulSoup import json import time from openpyxl.styles import Font, Alignment, Border, Side from openpyxl.utils import get_column_letter
def extract_info(url,position): response = requests.get(url) if response.status_code != 200: print(f"无法访问网页: {url}") return None
soup = BeautifulSoup(response.text, 'html.parser')
title = soup.find('h1', class_='entry-title').text.strip()
content = [] content_div = soup.find('div', class_='entry-content') paragraphs = content_div.find_all('p') for paragraph in paragraphs: if paragraph.a: links = paragraph.find_all('a') for link in links: content.append({ 'title': link.text.strip(), 'src': link['href'] }) continue if paragraph.img: imgs = paragraph.find_all('img') i = 1 for img in imgs: content.append({ 'title': '图片'+ str(i) +'-'+title, 'src': img['src'] }) i=i+1 continue else: content.append({ 'title': paragraph.text.strip(), 'src': '' }) ulists = content_div.find('ul') if(ulists): ulistsrcs = ulists.find_all('a') for ulistsrc in ulistsrcs: content.append({ 'title': ulistsrc.text.strip(), 'src': ulistsrc['href'] }) olists = content_div.find('ol') if(olists): olistsrcs = olists.find_all('a') for olistsrc in olistsrcs: content.append({ 'title': olistsrc.text.strip(), 'src': olistsrc['href'] }) figures = content_div.find_all('figure') if figures: for figure in figures: figure_links = figure.find_all('a') len_links = len(figure_links) for i in range(len_links - 1): content.append({ 'title': figure_links[i].text.strip(), 'src': figure_links[i]['href'] })
if len(content)!= 0: result = { 'title': title, 'content': content, 'position':position, } print(result) return result errschool.append(title) return
all_results = []
errschool = []
def creat_excel(data,location): workbook = openpyxl.Workbook()
worksheet = workbook.active worksheet.title = "Data"
title_font = Font(size=12, bold=True) title_alignment = Alignment(vertical='center') url_font = Font(color="0000FF", underline="single") border = Border(left=Side(style='thin'), right=Side(style='thin'), top=Side(style='thin'), bottom=Side(style='thin'))
worksheet['A1'] = "学校" worksheet['B1'] = "位置" worksheet['C1'] = "内容" worksheet['D1'] = "链接"
for col_letter in ['A', 'B', 'C','D']: cell = worksheet[f'{col_letter}1'] cell.font = title_font cell.alignment = title_alignment
row_num = 2 for item in data: title = item['title'] position = item['position']
end_row = row_num + len(item['content']) - 1
for content_item in item['content']: content_title = content_item['title'] content_src = content_item['src']
worksheet[f'A{row_num}'] = title worksheet[f'B{row_num}'] = position worksheet[f'C{row_num}'] = content_title worksheet[f'D{row_num}'] = content_src
for col_letter in ['C', 'D']: cell = worksheet[f'{col_letter}{row_num}'] cell.border = border
for col_letter in ['A', 'B']: cell = worksheet[f'{col_letter}{row_num}'] cell.border = border cell.alignment = title_alignment cell.font = title_font worksheet[f'D{row_num}'].font = url_font worksheet[f'D{row_num}'].hyperlink = content_src
row_num += 1
worksheet.merge_cells(f'A{row_num - len(item["content"])}:A{end_row}') worksheet.merge_cells(f'B{row_num - len(item["content"])}:B{end_row}') row_num += 1
for column in worksheet.columns: max_length = 0 column = [cell for cell in column] for cell in column: try: if len(str(cell.value)) > max_length: max_length = len(cell.value) except: pass adjusted_width = (max_length + 2) worksheet.column_dimensions[get_column_letter(column[0].column)].width = adjusted_width worksheet.column_dimensions['A'].width = 32 worksheet.column_dimensions['B'].width = 9 worksheet.column_dimensions['C'].width = 60 output_excel_path = f'./excelInfo/{location}.xlsx' workbook.save(output_excel_path) print(f"数据已成功写入 {output_excel_path}")
def creat_json(data,location): output_file_path = f'./jsonInfo/{location}.json' with open(output_file_path, 'w', encoding='utf-8') as json_file: json.dump(data, json_file, ensure_ascii=False, indent=4) print(f"数据已成功写入 {output_file_path}")
if __name__ == '__main__': main_url = "http://www.xiaoyuanzhaopin.net/fjsyxx/" location = '福建' main_response = requests.get(main_url) main_soup = BeautifulSoup(main_response.text, 'html.parser') main_content = main_soup.find('div',class_='entry-content') tables = main_content.find_all('table') main_links=[] for table in tables: td_elements = table.find_all('td') for td in td_elements: a_elements = td.find_all('a') if len(a_elements)==2: link = { 'position': a_elements[0].text.strip(), 'text': a_elements[1].text.strip(), 'href': a_elements[1]['href'] } main_links.append(link) for link in main_links: time.sleep(0.7) link_url = link.get('href') result = extract_info(link_url,link.get('position')) if result: all_results.append(result)
creat_json(all_results,location) creat_excel(all_results,location) print(len(all_results)) print(errschool)
|