import requests from bs4 import BeautifulSoup import csv def extract_text_from_element(element): """Recursively extracts text from an element, avoiding duplication.""" if element is None: return "" text = "" for child in element.children: if isinstance(child, str): text += child.strip() + " " elif child.name in ["ul", "ol"]: text += "\n" for li in child.find_all("li"): text += "- " + li.text.strip() + "\n" elif child.name == "br": text += "\n" elif child.name == "p": text += child.text.strip() + "\n" else: text += extract_text_from_element(child) return text.strip() def scrape_medlineplus_data(): # Renamed function for clarity base_url = "https://medlineplus.gov/ency/" start_urls = [ "https://medlineplus.gov/ency/encyclopedia_A.htm", "https://medlineplus.gov/ency/encyclopedia_B.htm", "https://medlineplus.gov/ency/encyclopedia_C.htm", "https://medlineplus.gov/ency/encyclopedia_D.htm", "https://medlineplus.gov/ency/encyclopedia_E.htm", "https://medlineplus.gov/ency/encyclopedia_F.htm", "https://medlineplus.gov/ency/encyclopedia_G.htm", "https://medlineplus.gov/ency/encyclopedia_H.htm", "https://medlineplus.gov/ency/encyclopedia_I.htm", "https://medlineplus.gov/ency/encyclopedia_J.htm", "https://medlineplus.gov/ency/encyclopedia_K.htm", "https://medlineplus.gov/ency/encyclopedia_L.htm", "https://medlineplus.gov/ency/encyclopedia_M.htm", "https://medlineplus.gov/ency/encyclopedia_N.htm", "https://medlineplus.gov/ency/encyclopedia_O.htm", "https://medlineplus.gov/ency/encyclopedia_P.htm", "https://medlineplus.gov/ency/encyclopedia_Q.htm", "https://medlineplus.gov/ency/encyclopedia_R.htm", "https://medlineplus.gov/ency/encyclopedia_S.htm", "https://medlineplus.gov/ency/encyclopedia_T.htm", "https://medlineplus.gov/ency/encyclopedia_U.htm", "https://medlineplus.gov/ency/encyclopedia_V.htm", "https://medlineplus.gov/ency/encyclopedia_W.htm", "https://medlineplus.gov/ency/encyclopedia_X.htm", "https://medlineplus.gov/ency/encyclopedia_Y.htm", "https://medlineplus.gov/ency/encyclopedia_Z.htm", "https://medlineplus.gov/ency/encyclopedia_0-9.htm" ] all_data = [] for start_url in start_urls: # Loop through all start URLs try: response = requests.get(start_url) response.raise_for_status() soup = BeautifulSoup(response.content, "html.parser") links = soup.find("ul", id="index").find_all("a") for link in links: href = link.get("href") if href: article_url = base_url + href print(f"Scraping: {article_url}") try: article_response = requests.get(article_url) article_response.raise_for_status() article_soup = BeautifulSoup(article_response.content, "html.parser") topic_element = article_soup.find("h1", class_="with-also", itemprop="name") topic = topic_element.text.strip() if topic_element else "N/A" summary_element = article_soup.find("div", id="ency_summary") summary = extract_text_from_element(summary_element) if summary_element else "N/A" q_and_a = [] main_div = article_soup.find("div", class_="main") if main_div: sections = main_div.find_all("section") for section in sections: question_title_element = section.find("div", class_="section-title") if question_title_element and question_title_element.find("h2") and \ "References" not in question_title_element.text and \ "Review Date" not in question_title_element.text and \ "Citation" not in question_title_element.text: question_text = question_title_element.find("h2") question = f"{topic} {question_text.text.strip()}?" if question_text else f"{topic} N/A?" answer_element = section.find("div", class_="section-body") answer = extract_text_from_element(answer_element) if answer_element else "N/A" q_and_a.append({"question": question, "answer": answer}) if q_and_a: all_data.append({ "topic": topic, "summary": summary, "q_and_a": q_and_a }) except requests.exceptions.RequestException as e: print(f"Error fetching article {article_url}: {e}") except Exception as e: print(f"Error processing {article_url}: {e}") except requests.exceptions.RequestException as e: print(f"Error fetching index page {start_url}: {e}") # Print error for each index page except Exception as e: print(f"Unexpected error: {e}") with open("medlineplus_all.csv", "w", newline="", encoding="utf-8") as csvfile: # Changed filename fieldnames = ["topic", "summary", "question", "answer"] writer = csv.DictWriter(csvfile, fieldnames=fieldnames) writer.writeheader() for item in all_data: base_row = { "topic": item["topic"], "summary": item["summary"], } if item["q_and_a"]: for qa in item["q_and_a"]: writer.writerow({ **base_row, "question": qa["question"], "answer": qa["answer"] }) if __name__ == "__main__": scrape_medlineplus_data() # Call the renamed function print("MedlinePlus data collection complete. Saved to medlineplus_all.csv")