该网站似乎使用了 JavaScript,因此当我加载检查代码时,我看不到列出医生的表格。但是,当您专门检查该元素时,它包含所有信息。
我尝试多次单击“加载更多”按钮,直到它消失,然后使用 BeautifulSoup 解析页面。
有人可以帮我解决为什么正在打印的 page_source 不显示任何信息吗?您是否需要设置一个 while 循环来完成单击“加载更多”直到它消失?
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver import ActionChains
import time
import requests
doctor_dict = {}
#configure webdriver
options = webdriver.ChromeOptions()
options.add_argument("--headless=new")
driver = webdriver.Chrome(options = options)
driver.get("https://www.globusmedical.com/patient-education-musculoskeletal-system-conditions/resources/find-a-surgeon/")
time.sleep(5)
clickable = driver.find_element(By.XPATH,'//button[@class="js-eml-load-more-button eml-load-more-button eml-btn btn btn--primary"]')
driver.execute_script("arguments[0].click();", clickable)
# items = driver.find_element(By.CLASS_NAME,"eml-location grid--item")
soup = BeautifulSoup(driver.page_source, 'html.parser')
print(soup.prettify())
driver.quit()
通过访问此URL,您可以轻松获取 JSON 对象形式的医生列表,而无需使用 Selenium 和 Beautiful Soup。要查找 URL,您只需在浏览器中导航到“检查”>“网络”>“XHR”即可。您可以按如下方式重写代码:
import requests
url = "https://www.globusmedical.com/wp-json/em-locator/v1/locations/?page=1"
headers = {'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:122.0) Gecko/20100101 Firefox/122.0'}
response = requests.get(url, headers=headers)
response_dict = response.json()