【发布时间】:2023-01-19 05:43:49
【问题描述】:
我需要从如下所示的网页中收集所有链接(每 206 个页面有 25 个链接,总共约 5200 个链接),它还有一个加载更多新闻按钮(三个点)。我写了我的脚本,但我的脚本没有提供我试图收集的任何链接。我更新了一些 Selenium 属性。我真的不知道为什么我无法获得所有链接。
from selenium import webdriver
from bs4 import BeautifulSoup
import time
from selenium.webdriver.common.by import By
from selenium.webdriver import Chrome
#Initialize the Chrome driver
driver = webdriver.Chrome()
driver.get("https://www.mfa.gov.tr/sub.en.mfa?ad9093da-8e71-4678-a1b6-05f297baadc4")
page_count = driver.find_element(By.XPATH, "//span[@class='rgInfoPart']")
text = page_count.text
page_count = int(text.split()[-1])
links = []
for i in range(1, page_count + 1):
# Click on the page number
driver.find_element(By.XPATH, f"//a[text()='{i}']").click()
time.sleep(5)
# Wait for the page to load
soup = BeautifulSoup(driver.page_source, 'html.parser')
# Extract the links from the page
page_links = soup.find_all('div', {'class': 'sub_lstitm'})
for link in page_links:
links.append("https://www.mfa.gov.tr"+link.find('a')['href'])
time.sleep(5)
driver.quit()
print(links)
我试图运行我的代码,但实际上我做不到。我需要为此找到一些解决方案。
【问题讨论】:
-
您使用 beautifulsoup 有什么原因吗?我问是因为看起来你只能用硒做任何事情
-
有时,使用 bs4 为我定位选择器变得很方便。
标签: javascript selenium web-scraping beautifulsoup