Я пытаюсь получить данные с первых трех страниц таблицы с разбивкой на страницы: https://www.fda.gov/safety/recalls-mark ... ety-alerts. Пока могу получить данные только с первой страницы. (У них есть API, но он обновляется только еженедельно, что для меня недостаточно часто).
Вот что у меня есть:
from selenium import webdriver
from selenium.webdriver.support.ui import Select
from bs4 import BeautifulSoup
import time
import json
# Base and target URLs
root = 'https://www.fda.gov'
website = f'{root}/safety/recalls-market-withdrawals-safety-alerts'
https://www.fda.gov/safety/recalls-market-withdrawals-safety-alerts
# Set up Selenium WebDriver
driver = webdriver.Chrome()
driver.get(website)
# Select "Food & Beverages" filter
dropdown = Select(driver.find_element("id", "edit-field-regulated-product-field"))
dropdown.select_by_value("2323") # 2323 corresponds to Food & Beverages
time.sleep(2) # Wait for the page to load
# Initialize data storage
recall_data = []
page_count = 0
max_pages = 1 # Set your page limit here
while page_count < max_pages:
# Parse the page content
soup = BeautifulSoup(driver.page_source, 'html.parser')
# Locate the table
table = soup.find('table', {'class': 'table'})
if not table:
break
# Extract data from the current page
rows = table.find_all('tr')[1:] # Skip header row
for row in rows:
cols = row.find_all('td')
if len(cols) > 1:
recall_info = {
'Date': cols[0].text.strip(),
'Brand Names': cols[1].text.strip(),
'Product Description': cols[2].text.strip(),
'Product Type': cols[3].text.strip(),
'Recall Reason Description': cols[4].text.strip(),
'Company Name': cols[5].text.strip(),
'Terminated Recall': cols[6].text.strip(),
}
recall_data.append(recall_info)
# Check for the "Next" button
try:
next_button = driver.find_element("xpath", "//a[contains(@class, 'sNext:Next')]")
next_button.click()
page_count += 1
time.sleep(2) # Wait for the next page to load
except Exception as e:
print("Next button not found or click failed, ending pagination.")
break
import csv
# Save data to CSV
csv_filename = 'recalls.csv'
# Define CSV header
csv_headers = [
'Date',
'Brand Names',
'Product Description',
'Product Type',
'Recall Reason Description',
'Company Name',
'Terminated Recall'
]
with open(csv_filename, 'w', newline='', encoding='utf-8') as csv_file:
writer = csv.DictWriter(csv_file, fieldnames=csv_headers)
# Write header
writer.writeheader()
# Write rows
writer.writerows(recall_data)
print(f"Data has been saved to {csv_filename}")
# Close the driver
driver.quit()
Я пробовал: проверять кнопку «Далее», добавлять «per_page=», «/max_rows» в URL-адрес, добавлять количество страниц/номера страниц в код, но пока я не могу пройти дальше первой страницы. Кнопка «Далее» есть, но в HTML-коде она не имеет такого обозначения.
Я пытаюсь получить данные с первых трех страниц таблицы с разбивкой на страницы: https://www.fda.gov/safety/recalls-market-withdrawals-safety-alerts. Пока могу получить данные только с первой страницы. (У них есть API, но он обновляется только еженедельно, что для меня недостаточно часто). Вот что у меня есть: [code]from selenium import webdriver from selenium.webdriver.support.ui import Select from bs4 import BeautifulSoup import time import json
# Base and target URLs root = 'https://www.fda.gov' website = f'{root}/safety/recalls-market-withdrawals-safety-alerts'
# Initialize data storage recall_data = [] page_count = 0 max_pages = 1 # Set your page limit here
while page_count < max_pages: # Parse the page content soup = BeautifulSoup(driver.page_source, 'html.parser')
# Locate the table table = soup.find('table', {'class': 'table'}) if not table: break
# Extract data from the current page rows = table.find_all('tr')[1:] # Skip header row for row in rows: cols = row.find_all('td') if len(cols) > 1: recall_info = { 'Date': cols[0].text.strip(), 'Brand Names': cols[1].text.strip(), 'Product Description': cols[2].text.strip(), 'Product Type': cols[3].text.strip(), 'Recall Reason Description': cols[4].text.strip(), 'Company Name': cols[5].text.strip(), 'Terminated Recall': cols[6].text.strip(), } recall_data.append(recall_info)
# Check for the "Next" button try: next_button = driver.find_element("xpath", "//a[contains(@class, 'sNext:Next')]") next_button.click() page_count += 1 time.sleep(2) # Wait for the next page to load except Exception as e: print("Next button not found or click failed, ending pagination.") break
with open(csv_filename, 'w', newline='', encoding='utf-8') as csv_file: writer = csv.DictWriter(csv_file, fieldnames=csv_headers)
# Write header writer.writeheader()
# Write rows writer.writerows(recall_data)
print(f"Data has been saved to {csv_filename}")
# Close the driver driver.quit() [/code] Я пробовал: проверять кнопку «Далее», добавлять «per_page=», «/max_rows» в URL-адрес, добавлять количество страниц/номера страниц в код, но пока я не могу пройти дальше первой страницы. Кнопка «Далее» есть, но в HTML-коде она не имеет такого обозначения.
Я пытаюсь получить данные с первых трех страниц таблицы с разбивкой на страницы: Пока могу получить данные только с первой страницы. (У них есть API, но он обновляется только еженедельно, что для меня недостаточно часто).
Вот что у меня есть:
from...
Веб-сайт основан на Java, и я пытаюсь разбить его на страницы, чтобы очистить данные, но разбиение на страницы не работает. Пожалуйста, помогите.
Вот сайт -
# Function to extract report IDs from the current page
def extract_report_ids():...
У меня есть сайт aspx, на котором есть форма, и когда вы ее заполняете, появляется всплывающее окно с html-таблицей, которую я хочу очистить. Всплывающее окно создается динамически, как в формате www.xyz.com/something/something/ Temp...