【发布时间】:2018-12-03 05:35:16
【问题描述】:
我正在尝试使用 python(Requests 和 BeautifulSoup4 库以及 Selenium)来抓取数据
当我尝试从网站中获取一些数据时,在延迟后加载数据时,它返回一个空值。我知道对于这项任务,我必须使用 WebDriverWait。
import requests
from bs4 import BeautifulSoup
# selenium imports
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
from selenium.common.exceptions import TimeoutException
# Initialize a Chrome webdriver
driver = webdriver.Chrome()
# Grab the web page
driver.get("http://")
# use selenium.webdriver.support.ui.Select
# that we imported above to grab the Select element called
# lmStatType, then select the first value
# We will use .find_element_by_name here because we know the name
dropdown = Select(driver.find_element_by_name("lmStatType"))
dropdown.select_by_value("1")
# select the year 2560
dropdown = Select(driver.find_element_by_name("lmYear"))
dropdown.select_by_value("60")
# Now we can grab the search button and click it
search_button = driver.find_elements_by_xpath("//*[contains(text(), 'ตกลง')]"[0]
search_button.click()
# we just look at .page_source of the driver
driver.page_source
# We can feed that into Beautiful Soup
doc = BeautifulSoup(driver.page_source, "html.parser")
# It's a tricky table, also tried with class names
rows = doc.find('table', id='datatable')
print(rows) # returns empty
在上面的例子中,我没有使用 selenium webdriver wait & timeout 相关语句的尝试选项来逐步理解它,即使我已经尝试了几种解决方法。
另外,刚刚尝试分别获取地区级别的数据(但无法弄清楚确切的类/id)
url = 'http://'
res = requests.get(url)
soup = BeautifulSoup(res.text,"lxml")
for tr in soup.find(class_="display").find_all("tr"):
data = [item.get_text(strip=True) for item in tr.find_all(["th","td"])]
print(data)
感谢任何帮助。提前致谢。抱歉,如果这是一个重复的问题。
【问题讨论】:
-
如果您可以直接从 /datasource/showStatProvince.php?statType=1&year=60" 获取数据 - 那可能会容易得多...
-
无法直接从url获取数据,因为是通过js函数处理的
-
当然可以。 HTML 中的 javascript-funktion 实际上为您提供了直接获取数据的正确 url。该端点返回 json...
-
不幸的是,一旦您发布,您就无法删除。您必须使用底部的联系我们链接请求解除关联。
标签: python selenium web-scraping beautifulsoup python-requests