|
| 1 | +from urllib.error import URLError |
| 2 | +from urllib.request import urlopen |
| 3 | + |
| 4 | +import re |
| 5 | +import pymysql |
| 6 | + |
| 7 | + |
| 8 | +def get_page_code(start_url, *, retry_times=3, charsets=('utf-8', )): |
| 9 | + try: |
| 10 | + for charset in charsets: |
| 11 | + try: |
| 12 | + html = urlopen(start_url).read().decode(charset) |
| 13 | + break |
| 14 | + except UnicodeDecodeError: |
| 15 | + html = None |
| 16 | + except URLError as ex: |
| 17 | + print('Error:', ex) |
| 18 | + return get_page_code(start_url, retry_times=retry_times - 1, charsets=charsets) if \ |
| 19 | + retry_times > 0 else None |
| 20 | + return html |
| 21 | + |
| 22 | + |
| 23 | +def main(): |
| 24 | + url_list = ['http://sports.sohu.com/nba_a.shtml'] |
| 25 | + visited_list = set({}) |
| 26 | + while len(url_list) > 0: |
| 27 | + current_url = url_list.pop(0) |
| 28 | + visited_list.add(current_url) |
| 29 | + print(current_url) |
| 30 | + html = get_page_code(current_url, charsets=('utf-8', 'gbk', 'gb2312')) |
| 31 | + if html: |
| 32 | + link_regex = re.compile(r'<a[^>]+href=["\'](.*?)["\']', re.IGNORECASE) |
| 33 | + link_list = re.findall(link_regex, html) |
| 34 | + url_list += link_list |
| 35 | + conn = pymysql.connect(host='localhost', port=3306, |
| 36 | + db='crawler', user='root', |
| 37 | + passwd='123456', charset='utf8') |
| 38 | + try: |
| 39 | + for link in link_list: |
| 40 | + if link not in visited_list: |
| 41 | + visited_list.add(link) |
| 42 | + print(link) |
| 43 | + html = get_page_code(link, charsets=('utf-8', 'gbk', 'gb2312')) |
| 44 | + if html: |
| 45 | + title_regex = re.compile(r'<h1>(.*)<span', re.IGNORECASE) |
| 46 | + match_list = title_regex.findall(html) |
| 47 | + if len(match_list) > 0: |
| 48 | + title = match_list[0] |
| 49 | + with conn.cursor() as cursor: |
| 50 | + cursor.execute('insert into tb_result (rtitle, rurl) values (%s, %s)', |
| 51 | + (title, link)) |
| 52 | + conn.commit() |
| 53 | + finally: |
| 54 | + conn.close() |
| 55 | + print('执行完成!') |
| 56 | + |
| 57 | + |
| 58 | +if __name__ == '__main__': |
| 59 | + main() |
| 60 | + |
0 commit comments