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
| import requests import re from bs4 import BeautifulSoup from pymysql import Error from urllib.parse import urlparse from datetime import datetime import pickle import pymysql
def crawl_and_process(urls_to_crawl): conn = pymysql.connect(host='', user='root', password='', database='search')
cursor = conn.cursor()
cursor.execute('SELECT MAX(policy_id) FROM search_policy') result = cursor.fetchone() max_id = result[0] if result[0] else 0 new_id = int(max_id) + 1 print(23,new_id) new_id = str(new_id) try: with open('data.pickle', 'rb') as f: visited_urls = pickle.load(f) print(visited_urls) except FileNotFoundError: visited_urls = set() data1 =[] count1 = 0 count2 = 0 data2=[] sql1 = 'INSERT INTO search_policy (policy_id, policy_title, pub_time, pub_agency, policy_body,policy_grade) VALUES (%s, %s, %s, %s, %s, %s)' sql2 = 'INSERT INTO search_policy (policy_id, policy_title, pub_agency,pub_time,UPDATE_DATE,pub_number, policy_body,policy_grade) VALUES (%s, %s, %s, %s, %s, %s, %s, %s)' for url in urls_to_crawl: if url in visited_urls: continue if '/content/' not in url: print('正在爬取:', url) data1.append(relativeurl(url,new_id)) new_id = int(new_id) + 1 print(52,new_id) new_id = str(new_id) else: print('正在爬取:', url) data2.append(absoluteurl(url,new_id)) new_id = int(new_id) + 1 new_id = str(new_id) print(64) visited_urls.append(url) print(66,) if len(data1) > 0: print('enter') try: cursor.executemany(sql1, data1) conn.commit() except Error as e: print(e) conn.rollback() print('ok') if len(data2) > 0: print('enter') cursor.executemany(sql2, data2) conn.commit() print('ok') print(74) with open('data.pickle', 'wb') as f: pickle.dump(visited_urls, f) cursor.close() conn.close()
def is_relative_url(url): parsed_url = urlparse(url) return not bool(parsed_url.netloc)
def relativeurl(url,new_id): UA = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36' headers = {'User_Agent': UA}
r = requests.get(url, headers=headers) r.encoding = 'utf-8'
soup = BeautifulSoup(r.text, 'lxml')
title_element = soup.find('h1') title = title_element.get_text().strip() pages_date = soup.find('div', class_='pages-date')
publish_time = pages_date.contents[0].strip() publish_time = datetime.strptime(publish_time, '%Y-%m-%d %H:%M') source = pages_date.find('span', class_='font').text.strip().replace('来源:', '') pages_content = soup.find('div', id='UCAP-CONTENT') p_tags = pages_content.find_all('p') text = '' for p_tag in p_tags: if p_tag.find('span'): p_tag.find('span').extract() text += p_tag.text.strip() + '\n' data = (new_id,title, publish_time, source, text,'国家级') print(125) return data
def absoluteurl(url,new_id): UA = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36' headers = {'User_Agent': UA} print('正在爬取:', url) r = requests.get(url, headers=headers) r.encoding = 'utf-8' soup = BeautifulSoup(r.text, 'lxml') info_table = soup.find('table', {'class': 'bd1'})
rows = info_table.find_all('tr')
topic_category = rows[0].find_all('td')[3].text.strip() publishing_organization = rows[1].find_all('td')[1].text.strip() title = rows[2].find_all('td')[1].text.strip() document_number = rows[3].find_all('td')[1].text.strip() written_date = rows[1].find_all('td')[3].text.strip() release_date = rows[3].find_all('td')[3].text.strip() written_date = datetime.strptime(written_date, '%Y年%m月%d日') release_date = datetime.strptime(release_date, '%Y年%m月%d日')
pages_content = soup.find('td', id='UCAP-CONTENT')
p_tags = pages_content.find_all('p')
text = '' for p_tag in p_tags: if p_tag.find('span'): p_tag.find('span').extract() text += p_tag.text.strip() + '\n' data = (new_id,title,publishing_organization,written_date,release_date,document_number,text,'国家级') return data
UA = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36' headers = {'User_Agent': UA} for page in range(1, 83): cn = f'http://sousuo.gov.cn/column/30469/{page}.htm' try: r = requests.get(cn, headers=headers) r.encoding = 'utf-8'
soup = BeautifulSoup(r.text, 'lxml') links = soup.find_all(href=re.compile('content')) urls = [] for link in links: url = link.get('href') urls.append(str(url)) print(urls) crawl_and_process(urls)
except: pass
|