Anvisa Categories Module
drugslm.sources.anvisa.categories
ANVISA Drug Categories Scraper.
This module is responsible for the extraction of drug listing data from ANVISA's search interface, categorized by regulatory definitions. It navigates through pagination, extracts tabular data, and consolidates it for downstream processing.
Scope
This module is responsible for: - Iterating through specific regulatory categories (IDs 1-12). - Handling Selenium pagination and table parsing. - Persisting raw chunks of data to avoid data loss during long runs. - Consolidating chunks into a final Pickle/CSV dataset. - Checking consistency between fetched metadata and scraped data.
This module is not responsible for: - Downloading PDFs or leaflets (handled by a separate downloader module). - Parsing the content of the leaflets. - Interacting with the "DADOS_ABERTOS_MEDICAMENTOS.csv" metadata file.
Execution Flow
- Scan (
crawl): : Initializes the category-based search list scan by checking the first and last page. - Orchestration (
scrape): Initializes thread pool and manages directory setup. - Unit Execution (
scrape_unit): Instantiates a WebDriver for a specific category. - Navigation (
scrape_pages): Accesses the category URL and iterates through pages. - Extraction (
table2data): Parses HTML tables into structured lists. - Persistence (
save_chunk): Saves intermediate data (chunks) to disk. - Consolidation (
join_chunks): Merges all chunks into a single dataset.
Data Persistence
- Chunks: Temporary
.pklfiles saved per page indata/raw/anvisa/categories/chunks/. - Progress:
progress.csvtracks the last successfully saved page per category. - Final Output:
categories.pklandcategories.csvcontaining the consolidated dataframe. - Metadata:
crawled.csvcontaining the expected number of items per category.
Prerequisites
- Selenium Grid (Hub) running and accessible via
HUB_URL. - Firefox/Chrome nodes connected to the Hub.
Known Limitations
- Dependent on specific XPath structures (
XPATH_PAGINATION,XPATH_PAGE_COUNT). UI changes on the ANVISA portal may break the scraper. - The "Items per page" selector is fragile and may fail if the DOM loads slowly.
CATEGORIES_COLUMNS = ['id', 'page', 'drug', 'link', 'company', 'protocol', 'pub_date']
module-attribute
list[str]: Column names for the final scraped dataset.
CATEGORIES_DIR = ANVISA_DIR / 'categories'
module-attribute
Path: Main directory for storing category-related data.
CATEGORIES_FILE = CATEGORIES_DIR / 'categories.pkl'
module-attribute
Path: Final consolidated output file containing all scraped data.
CATEGORIES_ID = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
module-attribute
list[int]: List of regulatory category IDs to be scraped from the ANVISA portal.
CATEGORIES_URL = ANVISA_URL + '?categoriasRegulatorias=%s'
module-attribute
str: Template URL for the search page, expecting a category ID as a parameter.
CHUNKS_DIR = CATEGORIES_DIR / 'chunks'
module-attribute
Path: Directory for temporary pickle files containing page-level data.
CRAWL_FILE = CATEGORIES_DIR / 'crawled.csv'
module-attribute
Path: File storing metadata (count/pages) fetched from the portal for validation.
METADATA_COLUMNS = ['id', 'items_page', 'last_page', 'size']
module-attribute
list[str]: Column names for the metadata (crawled) file.
PROGRESS_FILE = CATEGORIES_DIR / 'progress.csv'
module-attribute
Path: File tracking the scraping progress to allow resuming execution.
SLEEPSECS = 1
module-attribute
int: Time in seconds to wait between page transitions to avoid rate limiting.
WAITSECS = 5
module-attribute
int: Maximum time in seconds to wait for an element to appear (Explicit Wait).
XPATH_CURRENT_PAGE = f'{XPATH_PAGINATION}//li[contains(@class, 'active')]//a'
module-attribute
str: XPath to locate the currently active page number.
XPATH_LAST_PAGE = f'{XPATH_PAGINATION}//a[contains(@ng-switch-when, 'last')]'
module-attribute
str: XPath to locate the 'Last' button in pagination.
XPATH_PAGE_COUNT = "//div[contains(@class, 'ng-table-counts')]"
module-attribute
str: XPath to locate the 'items per page' dropdown/buttons container.
XPATH_PAGINATION = "//ul[contains(@class, 'pagination')]"
module-attribute
str: XPath to locate the pagination container.
check_categories(category_id=None)
Checks the consistency between the local categories and the ANVISA database.
Compares the row count of the local consolidated file against the metadata fetched from the live site (crawled file).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
category_id
|
int | None
|
ID to check specific category consistency. If None, checks global consistency. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
The difference between expected and found records (expected - found). |
Source code in drugslm/sources/anvisa/categories.py
632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 | |
crawl()
Orchestrates metadata fetching for all categories listed in CATEGORIES_ID.
Generates a CSV file (CRAWL_FILE) containing the number of items and pages for each category, which serves as the baseline for validation.
Source code in drugslm/sources/anvisa/categories.py
1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 | |
crawl_unit(driver, category_id)
Navigates to the first and last page of a category to estimate data volume.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
driver
|
WebDriver
|
The active Selenium WebDriver instance. |
required |
category_id
|
int
|
The regulatory category ID. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
list |
list
|
A list containing ["id", "page_size", "last_page", "size"]. |
Source code in drugslm/sources/anvisa/categories.py
910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 | |
delete_chunks(category_id=None)
Deletes temporary chunk files from the chunk directory.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
category_id
|
int | None
|
If provided, deletes only chunks for that category. If None, deletes all chunks in the directory. |
None
|
Source code in drugslm/sources/anvisa/categories.py
523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 | |
delete_lock_progress()
Removes stale lock files from previous executions to prevent deadlocks.
This should be called only during single-threaded orchestration (start of pipeline).
Source code in drugslm/sources/anvisa/categories.py
509 510 511 512 513 514 515 516 517 518 519 520 | |
find_table(driver)
Waits for the main results table to be present in the DOM.
Uses visual helpers (scroll and highlight) to assist debugging and visibility.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
driver
|
WebDriver
|
The active Selenium WebDriver instance. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
WebElement |
WebElement
|
The found |
Raises:
| Type | Description |
|---|---|
TimeoutException
|
If the table is not found within the timeout period (after retries). |
Source code in drugslm/sources/anvisa/categories.py
357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 | |
get_categories()
Loads the final consolidated categories DataFrame.
Returns:
| Name | Type | Description |
|---|---|---|
DataFrame | None
|
pd.DataFrame: Consolidated categories DataFrame. |
|
None |
DataFrame | None
|
If the file is missing or empty. |
Source code in drugslm/sources/anvisa/categories.py
575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 | |
get_crawled(category_id=None)
Loads the crawled metadata file.
Can return the entire DataFrame or filter for a specific category size.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
category_id
|
int | None
|
Optional ID to filter specific size. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
DataFrame | None
|
pd.DataFrame: All metadata or specific row if category_id passed. |
|
None |
DataFrame | None
|
If not found or error. |
Source code in drugslm/sources/anvisa/categories.py
593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 | |
get_last_processed_page(category_id)
Retrieves the last successfully processed page and the table size at that time.
Used to resume execution from a specific point.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
category_id
|
int
|
The category ID to check. |
required |
Returns:
| Type | Description |
|---|---|
DataFrame | None
|
pd.DataFrame: The last progress entry found for category_id, or None. |
Source code in drugslm/sources/anvisa/categories.py
682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 | |
get_pages(driver)
Captures the current state of pagination controls and the next page element.
Retries on failure (e.g., StaleElementReferenceException, TimeoutException).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
driver
|
WebDriver
|
The active Selenium WebDriver instance. |
required |
Returns:
| Type | Description |
|---|---|
Tuple[dict, WebElement | None, WebElement | None]
|
Tuple[dict, WebElement, WebElement]: A tuple containing: - dict: A dictionary with keys 'current', 'next', and 'last' (all integers). - WebElement: The Selenium element corresponding to the next page button (or None). - WebElement: The Selenium element corresponding to the last page button (or None). |
Raises:
| Type | Description |
|---|---|
TimeoutException
|
If the pagination container is not found (caught internally, returns default). |
Source code in drugslm/sources/anvisa/categories.py
262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 | |
goto_last_processed_page(driver, target_page)
Navigates directly to the target_page using a sliding window strategy.
Optimizes the path by choosing to start from the beginning or the end (Last Page), then iterating through the visible pagination window until the target is found.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
driver
|
WebDriver
|
The active Selenium WebDriver instance. |
required |
target_page
|
int
|
The page number to reach. |
required |
Raises:
| Type | Description |
|---|---|
Exception
|
If navigation fails. |
Source code in drugslm/sources/anvisa/categories.py
714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 | |
join_chunks(force=False)
Consolidates all individual page pickle files into a single DataFrame.
It can either overwrite the existing final file or merge new chunks with the existing data, handling deduplication based on 'protocol'.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
force
|
bool
|
If True, completely overwrites the existing categories file. If False, merges new chunks with existing data based on protocol number. |
False
|
Source code in drugslm/sources/anvisa/categories.py
444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 | |
resolve_next_page(current_page, last_page)
Parses pagination WebElements to extract page numbers and calculate the next target.
Validates that the text content of the elements is numeric before converting.
Logic ensures next_page does not exceed last_page.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
current_page
|
WebElement
|
The WebElement representing the currently active page. |
required |
last_page
|
WebElement
|
The WebElement representing the last available page. |
required |
Returns:
| Type | Description |
|---|---|
Tuple[int, int, int]
|
Tuple[int, int, int]: (current_page_num, last_page_num, next_page_num). |
Raises:
| Type | Description |
|---|---|
AssertionError
|
If element text is not numeric. |
ValueError
|
If conversion to integer fails. |
Source code in drugslm/sources/anvisa/categories.py
325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 | |
rotate_file(filepath)
Renames a file by appending a timestamp, acting as a backup rotation.
Example: data.csv -> data_20231027103000.csv
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filepath
|
Path
|
Path object to the file to be rotated. |
required |
Source code in drugslm/sources/anvisa/categories.py
394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 | |
run(n_threads=1, force=False, check=False, crawl_only=False, skip_crawl=False)
Runs the ANVISA drug listing scraper pipeline.
Source code in drugslm/sources/anvisa/categories.py
1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 | |
save_chunk(raw_data, category_id, page_num)
Saves a single page of scraped data to a pickle file (chunk).
Adds metadata columns (category_id, page_num) to the raw data before saving.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
raw_data
|
list
|
The raw data list extracted from the table. |
required |
category_id
|
int
|
The category ID being processed. |
required |
page_num
|
int
|
The current page number. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
The number of rows saved. |
Source code in drugslm/sources/anvisa/categories.py
418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 | |
save_progress(category_id, pages, saved_size)
Appends execution progress to a CSV file with file locking.
This ensures that multiple threads do not corrupt the progress file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
category_id
|
int
|
The category ID being processed. |
required |
pages
|
dict
|
Pagination state dictionary {'current', 'next', 'last'}. |
required |
saved_size
|
int
|
Number of rows saved in this step. |
required |
Source code in drugslm/sources/anvisa/categories.py
551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 | |
scrape(n_threads=1, force=False)
Orchestrates the parallel scraping of all categories.
Manages the lifecycle of the scraping process: 1. Prepares the environment (creates dirs, cleans chunks if force=True). 2. Distributes scraping tasks across a thread pool. 3. Consolidates results into a single file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_threads
|
int
|
Number of concurrent threads to use. Defaults to 1. |
1
|
force
|
bool
|
If True, deletes all previous chunks and starts fresh. |
False
|
Source code in drugslm/sources/anvisa/categories.py
966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 | |
scrape_pages(driver, category_id, force=False)
Iterates through all pages of a specific regulatory category.
Extracts table data, saves checkpoints, and handles pagination.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
driver
|
WebDriver
|
The active Selenium WebDriver instance. |
required |
category_id
|
int
|
The ID of the regulatory category to scrape. |
required |
force
|
bool
|
If True, ignores previous progress and starts from page 1. Defaults to False. |
False
|
Source code in drugslm/sources/anvisa/categories.py
783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 | |
scrape_unit(category_id, force=False)
Orchestrates the scraping process for a single regulatory category.
This function acts as an isolated worker that:
1. Validates the category against crawled metadata.
2. Manages the lifecycle of a dedicated Selenium WebDriver instance.
3. Delegates the actual extraction logic to scrape_pages.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
category_id
|
int
|
The unique identifier of the regulatory category. |
required |
force
|
bool
|
If True, forces a fresh scrape ignoring previous progress. |
False
|
Source code in drugslm/sources/anvisa/categories.py
878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 | |
sel_max_items_page(driver)
Attempts to select the highest available "items per page" option (e.g., 50).
Iterates through options in reverse order (highest to lowest). If the highest option fails, it tries the next lower one. Exceptions are swallowed to prevent script execution stoppage, defaulting to 0 if unsuccessful.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
driver
|
WebDriver
|
The active Selenium WebDriver instance. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
The selected items per page value. Returns 0 if failed. |
Source code in drugslm/sources/anvisa/categories.py
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 | |
table2data(element)
Parses the HTML table element and extracts rows into a list of data.
Uses BeautifulSoup for efficient parsing of the inner HTML of the WebElement.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
element
|
WebElement
|
The Selenium WebElement containing the |
required |
Returns:
| Name | Type | Description |
|---|---|---|
list |
list
|
A list of lists, where each inner list represents a row: [drug, link, company, protocol, pub_date]. Returns empty list [] on failure. |
Source code in drugslm/sources/anvisa/categories.py
199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 | |