【问题标题】:Scrape dynamic content in Python在 Python 中抓取动态内容
【发布时间】:2015-07-18 19:20:00
【问题描述】:
【问题讨论】:
标签:
javascript
python
scrapy
【解决方案1】:
在处理动态站点时,比常规方式更难抓取数据。但首先我们已经确定了数据是如何在页面中动态呈现的。
数据可能以下列方式呈现:
- 来自包含数据的 javascript 文件。
- 来自 ajax 响应。
- 来自 websocket 响应。在这种情况下,我们必须先发送一个
给服务器的相关消息,它给我们一个响应,这可能
包含数据。
-
来自 api 响应。
会有比我提到的更多的方法。
在您的情况下,数据是从这个api_request_url 获得的。
下图显示了我们在向 api_request_url 请求期间需要提供的 form_data。
下面是 json_response 显示
其中包含您需要的数据。
如果您更改form_data中的参数,您将获得相应的数据。
【解决方案2】:
我不确定scrapy,所以我不能帮你,但你可以试试selenium。下面的代码应该适用于动态生成的内容。
import time
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions
driver = webdriver.Firefox()
url = "www.google.com"
driver.get(url)
# If it takes a certain amount of time for the content to be created you can
# use time.sleep
time.sleep(5)
# However if you want to wait for specified content to appear, you
# can use the following
try:
WebDriverWait(driver, 10).until(
expected_conditions.presence_of_element_located(
(By.ID, "id-of-your-element")
)
finally:
driver.quit()
# then you can pull your html
html = driver.page_source
Selenium 也有很棒的 docs。这里的大部分代码实际上都可以在文档中找到。