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
| conn.execute("INSERT OR IGNORE INTO web_docs (url) VALUES (?)", (URL,))
try: while row := conn.execute( "SELECT url FROM web_docs WHERE status='pending' ORDER BY rowid LIMIT 1" ).fetchone(): page_url = row[0]
try: response = session.get(page_url, timeout=timeout) response.raise_for_status() html_content = response.content soup = BeautifulSoup(html_content, "html.parser") except requests.exceptions.HTTPError as e: logger.warning(f'request "{page_url}" failed: {e}') cursor.execute( "UPDATE web_docs SET attempts=attempts+1 WHERE url = ?", (page_url,) ) cursor.execute( f"UPDATE web_docs SET status='failed' WHERE url = ? AND attempts>={max_attempts}", (page_url,), ) conn.commit() continue
new_links = [] for a_link in tqdm(soup.find_all("a"), desc=page_url): href = str(a_link.get("href", "")) if not href: logger.debug(f'link: "{a_link}" has no href attribute') continue
next_url, frag = urldefrag(urljoin(page_url, href)) host = urlparse(next_url).hostname
if host != base_host: logger.debug( f'skip "{next_url}" because "{host}" not equal to "{base_host}"' ) continue new_links.append(next_url)
cursor.execute( "UPDATE web_docs SET content=?, status='done' WHERE url=?", (html_content, page_url), ) cursor.executemany( "INSERT OR IGNORE INTO web_docs (url) VALUES (?)", [(u,) for u in new_links] ) conn.commit()
logger.info("Success")
except KeyboardInterrupt: conn.commit() logger.info("Interrupted, progress is safe in sqlite.db") finally: conn.close()
|